您的位置:首页 > 编程语言 > PHP开发

php中SimpleXML的使用方法,加载XML,解析XML

2016-08-07 11:49 801 查看
首先先创建一个XML文件,post.xml,内容如下:

<?xml version="1.0" standalone="yes"?>
<library>
<book>
<title>hahhah</title>
<author gender="female">Tom Lusten</author>
<description>Jane Austen's most popular work.</description>
</book>
<book>
<title>prindesfjkafg</title>
<author gender="male" age="20">Luck Aun</author>
<description>Jane Austen's most popular work.</description>
</book>
<book>
<title>nihao</title>
<author gender="female">Luck Aun</author>
<description>Jane Austen's most popular work.</description>
<cast>
<character>Jane ma ldfejt.</character>
<character>Jack is a children.</character>
<character>I'm very happy!</character>
<character>Lady Barnes</character>
</cast>
</book>
</library>


一、加载XML

1.加载xml文件

simplexml_load_file( )将xml文件加载到对象

$xml = simplexml_load_file("post.xml");
var_dump($xml);


打印结果如下:

object(SimpleXMLElement)#1 (1) {
["book"]=>
array(3) {
[0]=>
object(SimpleXMLElement)#2 (3) {
["title"]=>
string(6) "hahhah"
["author"]=>
string(10) "Tom Lusten"
["description"]=>
string(32) "Jane Austen's most popular work."
}
[1]=>
object(SimpleXMLElement)#3 (3) {
["title"]=>
string(13) "prindesfjkafg"
["author"]=>
string(8) "Luck Aun"
["description"]=>
string(32) "Jane Austen's most popular work."
}
[2]=>
object(SimpleXMLElement)#4 (4) {
["title"]=>
string(5) "nihao"
["author"]=>
string(8) "Luck Aun"
["description"]=>
string(32) "Jane Austen's most popular work."
["cast"]=>
object(SimpleXMLElement)#5 (1) {
["character"]=>
array(4) {
[0]=>
string(15) "Jane ma ldfejt."
[1]=>
string(19) "Jack is a children."
[2]=>
string(15) "I'm very happy!"
[3]=>
string(11) "Lady Barnes"
}
}
}
}
}


2.加载xml字符串

simplexml_load_string( ),作用与simplexml_load_file( )相同,知识输入参数为字符串形式。

3.加载xml DOM文档

simplexml_import_dom( )

二、解析xml

如下方式:

1.返回最初的XML文档,只是删除了换行字符,各个字符也转换为相应的HTML实体

echo htmlspecialchars($xml->asXML());


2.首先更多的了解元素,假设想要知道每位作者的名字

//打印出每一位作者
foreach($xml->book as $book) {
printf("%s is %s.<br />",$book->author,$book->author->attributes());
}


3.确定某本书作者的属性

echo $xml->book[0]->author->attributes();//打印某位作者属性


若作者的属性不只一个可用下面的方式:

//对作者属性进行遍历
foreach ($xml->book[1]->author->attributes() as $key => $value) {
printf("%s = %s <br />",$key,$value);
}


4.children( )函数,了解某个节点中的子节点

//对cast节点中的character进行遍历
foreach ($xml->book[2]->cast->children() as $character) {
echo $character."<br />";
}


5.xpath获取节点信息

//获取所有作者名
$authors = $xml->xpath('/library/book/author');
foreach ($authors as $author) {
echo "$author <br />";
}


6.xpath有选择的获取节点信息

//获取所有作者名为Luck Aun的书籍的title
$books = $xml->xpath("/library/book[author='Luck Aun']");
foreach($books as $titles) {
echo $titles->title.'<br />';
}


以上2-6种情况结果如下所示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: