1. simplexml
SimpleXML converts XML documents into objects, such as:
Element - A single property converted to a SimpleXMLElement object. When there are multiple elements at the same level, they are placed in an array.
Properties - Accessed using an associative array, where the subscripts correspond to the property names.
Element data - Text data from the element is converted to a string. If an element has multiple text nodes, they are arranged in the order in which they are found.
SimpleXML is very fast to use when performing basic tasks like:
Read XML file
Extract data from XML string
Edit text node or attribute
xml version="1.0" encoding="utf-8"?> <phplamp> <post> <title id="1">PHP XML处理介绍一</title> <details>详细内容一</details> </post> <post> <title id="2">PHP XML处理介绍二</title> <details>详细内容二</details> </post> <post> <title id="3">PHP XML处理介绍三</title> <details>详细内容三</details> </post> </phplamp> <?xml version="1.0" encoding="utf-8"?> <phplamp> <post> <title id="1">PHP XML处理介绍一</title> <details>详细内容一</details> </post> <post> <title id="2">PHP XML处理介绍二</title> <details>详细内容二</details> </post> <post> <title id="3">PHP XML处理介绍三</title> <details>详细内容三</details> </post> </phplamp> attributes() 获得属性
php /** * 加载Xml文件 */ $xml = simplexml_load_file("text.xml"); /** * 如果Xml为字符串的话可以用下面这个 方法,后面的使用方法一样 * $xml = simplexml_load_string */ /** * 遍历$xml对象 */ foreach ($xml as $key => $value) { // 获取属性 $attr = $value->title->attributes(); echo "Id: " . $attr['id'] . "</br>"; echo "Title: " . $value->title . "</br>"; echo "Details: " . $value->details . "</br></br>"; } ?> <?php /** * 加载Xml文件 */ $xml = simplexml_load_file("text.xml"); /** * 如果Xml为字符串的话可以用下面这个 方法,后面的使用方法一样 * $xml = simplexml_load_string */ /** * 遍历$xml对象 */ foreach ($xml as $key => $value) { // 获取属性 $attr = $value->title->attributes(); echo "Id: " . $attr['id'] . "</br>"; echo "Title: " . $value->title . "</br>"; echo "Details: " . $value->details . "</br></br>"; } ?>