XML (Extensible Markup Language) is widely used for storing and transferring data. In PHP, reading and writing XML files is a common operation. This article will walk you through how to use PHP's SimpleXML extension to perform these operations.
First, we need to prepare an XML file. Assume the file is named `data.xml` with the following content:
<users> <user> <name>Zhang San</name> <age>25</age> </user> <user> <name>Li Si</name> <age>30</age> </user> </users>
We can then use PHP's SimpleXML extension to read this XML file. SimpleXML is very easy to use; we simply call the `simplexml_load_file` function to load the XML file:
<?php // Load the XML file $xml = simplexml_load_file('data.xml'); // Iterate through XML nodes and output data foreach ($xml->user as $user) { echo 'Name: ' . $user->name . '<br>'; echo 'Age: ' . $user->age . '<br>'; echo '<br>'; } ?>
The above code will output each user's name and age from the XML file to the screen.
If we want to create a new XML file and write data to it, we can also use the SimpleXML extension.
<?php // Create an XML object $xml = new SimpleXMLElement('<users></users>'); // Add user information $user = $xml->addChild('user'); $user->addChild('name', 'Wang Wu'); $user->addChild('age', 35); // Save the XML object to a file $xml->asXML('new_data.xml'); ?>
The above code will create a new XML file `new_data.xml` and write a user's name and age to it.
These are the basic methods for reading and writing XML files in PHP using the SimpleXML extension. With these operations, we can easily handle XML data, whether it's reading existing files or creating new ones and writing data to them. For more complex XML operations, refer to the official PHP documentation for further details.