Home  >  Article  >  Backend Development  >  How to read and write XML files in PHP

How to read and write XML files in PHP

王林
王林Original
2023-07-28 10:53:411320browse

How to read and write XML files in PHP

XML is a markup language that is widely used to store and transmit data. Reading and writing XML files in PHP are very common operations, and this article will introduce how to use PHP to implement these operations.

Read XML file
First, we need to create an XML file. Assume that our XML file is named data.xml and the content is as follows:

<users>
  <user>
    <name>张三</name>
    <age>25</age>
  </user>
  <user>
    <name>李四</name>
    <age>30</age>
  </user>
</users>

Next, we use PHP SimpleXML extension to read the XML file. Using SimpleXML is very simple, we only need to use the simplexml_load_file function to load the XML file.

<?php
// 加载XML文件
$xml = simplexml_load_file('data.xml');

// 遍历XML节点并输出
foreach ($xml->user as $user) {
    echo "姓名:" . $user->name . "<br>";
    echo "年龄:" . $user->age . "<br>";
    echo "<br>";
}
?>

The above code will output the name and age of each user in the XML file to the screen.

Write XML file
If we want to create an XML file and write data to it, we can also use the SimpleXML extension to achieve this.

<?php
// 创建一个XML对象
$xml = new SimpleXMLElement('<users></users>');

// 添加用户信息
$user = $xml->addChild('user');
$user->addChild('name', '王五');
$user->addChild('age', 35);

// 将XML对象保存到文件
$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 into it.

The above is a simple example of using PHP to read and write XML files. Using the SimpleXML extension, we can easily read existing XML files, as well as create new XML files and write data to them. For more complex XML operations, you can refer to PHP official documentation and related tutorials for learning and application.

The above is the detailed content of How to read and write XML files 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