Home  >  Article  >  Backend Development  >  How to read XML file in PHP

How to read XML file in PHP

不言
不言Original
2019-02-18 10:15:125164browse

SimpleXML is a PHP extension introduced in PHP5, allowing users to easily process XML data in PHP. SimpleXML can convert any XML data into an object that can be easily processed using ordinary attribute selectors and array iterators.

How to read XML file in PHP

Note: The How to read XML file in PHP-simplexml extension must be installed on the system to use it.

Let’s look at specific examples

The code is as follows

<?xml version="1.0"?>
<company>
 <employee>
 <firstname>Tom</firstname>
 <lastname>Cruise</lastname>
 <designation>MD</designation>
 <salary>500000</salary>
 </employee>
 <employee>
 <firstname>Tyler</firstname>
 <lastname>Horne</lastname>
 <designation>CEO</designation>
 <salary>250000</salary>
 </employee>
</company>

Read specific XML elements

Use the simplexml_load_file function in PHP The program loads an external XML file and creates an object. Afterwards, any element in the XML can be accessed through this object as shown below.

<?How to read XML file in PHP
$xmldata = simplexml_load_file("employees.xml") or die("Failed to load");
echo $xmldata->employee[0]->firstname . "<\n>";
echo $xmldata->employee[1]->firstname; 
?>

The output is:

Tom
Tyler

Reading XML elements in a loop

In this example, we use the foreach method to iterate over the entire XML file and read elements from XML. Foreach loops through all children of an object.

<?How to read XML file in PHP
$xmldata = implexml_load_file("employees.xml") or die("Failed to load");
foreach($xmldata->children() as $empl) {         
 echo $empl->firstname . ", ";     
 echo $empl->lastname . ", ";     
 echo $empl->designation . ", ";        
 echo $empl->salary . "<\n>"; 
} 
?>

The output results are as follows

Tom, Cruise, MD, 500000
Tyler, Horne, CEO, 250000

This article ends here. For more exciting content, you can pay attention to other related column tutorials on the PHP Chinese website! ! !

The above is the detailed content of How to read XML file in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn