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

How to read XML file in PHP

不言
Release: 2023-04-05 09:40:02
Original
5215 people have browsed it

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>
Copy after login

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; 
?>
Copy after login

The output is:

Tom
Tyler
Copy after login

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>"; 
} 
?>
Copy after login

The output results are as follows

Tom, Cruise, MD, 500000
Tyler, Horne, CEO, 250000
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template