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

解读PHP DOMDocument在解析XML文件中的作用

2014-12-17 15:31 549 查看
在使用PHP对XML文件进行解析的时候,我们可以用很多方法。在这里,我们将为大家重点介绍如何使用PHP DOMDocument来及逆行能够XML文件的解析。

关于用到的XML文件还以“Php Xml处理之simplexml使用方法浅谈”一文中的XML为例,文件名为:me.xml。代码如下:

PHP XML处理XML代码

< ?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>

然后就需要用PHP DOMDocument去处理这个文件,将XML文件中的任何元素都解析出来。代码如下,里面有注释。

PHP DOMDocument解析XML文件的代码

< ?php
// 首先要建一个DOMDocument对象
$xml = new DOMDocument();

// 加载Xml文件
$xml->load("me.xml");

// 获取所有的post标签
$postDom = $xml->
getElementsByTagName("post");

// 循环遍历post标签
foreach($postDom as $post){
// 获取Title标签Node
$title = $post->
getElementsByTagName("title");

/**
* 要获取Title标签的Id属性要分两部走
* 1. 获取title中所有属性的
列表也就是$title->item(0)->attributes
* 2. 获取title中id的属性,
因为其在第一位所以用item(0)
*
* 小提示:
* 若取属性的值可以用item(*)->nodeValue
* 若取属性的标签可以用item(*)->nodeName
* 若取属性的类型可以用item(*)->nodeType
*/
echo "Id: " . $title->item(0)->
attributes->item(0)->nodeValue . "< br />";
echo "Title: " . $title->
item(0)->nodeValue . "< br />";
echo "Details: " . $post->
getElementsByTagName("details")->i
tem(0)->nodeValue . "< br />< br />";
}
?>

这只是一种方法,PHP DOMDocument相当强大,还有更多的解析方法与策略,等待您去发掘。

==============================================

获取属性值方法getAttribute:

$dom = new DOMDocument();

$xmlStr = file_get_contents('city_index.xml');

$dom->loadXML($xmlStr);

//$dom->load('city_index.xml');

$locationDom = $dom->getElementsByTagName("location");

foreach($locationDom as $locationNode)

{

$provinceXml=$locationNode->getAttribute('province');

$cityXml=$locationNode->getAttribute('city');

$countyXml=$locationNode->getAttribute('county');

echo $provinceAttr.$cityXml.$countyXml."<br>";

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