在PHP中对xml进行解析以及操作,可使用DOMDocument对象和simplexml。在这里我给大家介绍simplexml的使用方法,重点是xpath,对应XML节点的操作。
一、定义XML数据
<?php //定义XML数据 $string = <<<XML <?xml version='1.0' encoding="UTF-8"?> <library> <categories> <category cid="1">Web Development</category> <category cid="2">Jassss</category> <category cid="3">Jssss</category> <category cid="4">Java</category> <category cid="4"><a href="www.test.cn">test</a>testA</category> </categories> <books> <book bid="1" order="2"> <title>Apache 2</title> <author>Peter Wainwright</author> <publisher>Wrox</publisher> <category>1</category> </book> <book bid="2" order="4"> <title>Advanced PHP Programming</title> <author>George Schlossnagle</author> <publisher>Developer Library</publisher> <category>1</category> <category>3</category> </book> <book bid="3" order="1"> <title>Visual FoxPro 6 - Programmers Guide</title> <author>Eric Stroo</author> <publisher>Microsoft Press</publisher> <category>2</category> </book> <book bid="4" order="3"> <title>Mastering Java 2</title> <author>John Zukowski</author> <publisher>Sybex</publisher> <category>4</category> </book> </books> </library> XML;
二、使用xpath,查询所有category节点的数据
<?php $simple = simplexml_load_string($string); $cateArr = $simple->xpath('/library/categories/category'); foreach ($cateArr as $cate) { //获取节点属性 $attr = $cate->attributes(); $cid = $attr['cid']; echo "cid:{$cid}----{$cate}<br>"; //获取节点数据 $str = $cate->saveXML(); echo $str,'<br>'; }
<?php $simple = simplexml_load_string($string); $bookArr = $simple->xpath("/library/books/book[@bid='2']"); echo $bookArr[0]->title , '<br>'; echo $bookArr[0]->author , '<br>';
<?php $simple = simplexml_load_string($string); $bookArr = $simple->xpath("/library/books/book[publisher='Sybex']"); echo $bookArr[0]->title , '<br>'; echo $bookArr[0]->author , '<br>';
<?php $simple = simplexml_load_string($string); $cateArr = $simple->xpath("/library/categories/category[@cid='1' or @cid='2']"); foreach ($cateArr as $cate) { $attr = $cate->attributes(); //..... }
<?php $simple = simplexml_load_string($string); $cateArr = $simple->xpath("/library/categories"); $subCateArr = $cateArr[0]->xpath("category[@cid='4']"); foreach ($subCateArr as $subCate) { //... }
<?php //starts-width(string1, string2) 以string2开头 //contains(string1, string2) 包含string2 $simple = simplexml_load_string($string); //.代表当前节点值 $cateArr = $simple->xpath("/library/categories/category[starts-with(., 'Ja')]"); foreach ($cateArr as $cate) { $attr = $cate->attributes(); //... }
<?php $simple = simplexml_load_string($string); $cateArr = $simple->xpath('//category'); foreach ($cateArr as $cate) { $attr = $cate->attributes(); //... echo "{$cate}<br>"; }
八、查询子节点是否存在、并返回字节点的父节点
<?php $simple = simplexml_load_string($string); //"/parent::*"返回父节点 $cateArr = $simple->xpath("/library/books/book/test/parent::*"); foreach ($cateArr as $cate) { echo "{$cate->test}<br>"; }