PHP如何使用DOM和simplexml讀取xml文檔

來源:文萃谷 1.82W

導語:PHP如何使用DOM和simplexml讀取xml文檔呢?具體實現代碼請閲讀以下內容,更多詳情請關注應屆畢業生考試網。

PHP如何使用DOM和simplexml讀取xml文檔

<?xml version="1.0" encoding="utf-8"?>

<root>

<book>

<title>天龍八部</title>

<author>金庸</author>

</book>

<book>

<title>陸小鳳</title>

<author>古龍</author>

</book>

<book>

<title>倚天屠龍記</title>

<author>金庸</author>

</book>

<book>

<title>西遊記</title>

<author>吳承恩</author>

</book>

<book>

<title>神鵰俠侶</title>

<author>金庸</author>

</book>

<book>

<title>射鵰英雄傳</title>

<author>金庸</author>

</book>

</root>

  用DOM代碼實現:

  DOM讀取xml文檔步驟:1、創建DOM對象——》2、載入DOM文檔內容——》3、截取要讀取內容所在的標籤——》獲得要讀取的內容。

header('Content-type:text/html;charset=utf-8');

$arr=array();

$dom = new DOMDocument();//創建DOM對象

$dom->load('./');//載入xml文檔

print_r($dom);

echo '<hr>';

$dom = $dom->getElementsByTagName('book');//截取標籤

for($i=0;$i<$dom->length;$i++){

if($dom->item($i)->childNodes->item(1)->childNodes->item(0)->wholeText=='金庸'){

$arr[] = $dom->item($i)->childNodes->item(0)->childNodes->item(0)->wholeText.'<br />';//獲取內容

}

}

print_r($arr);

使用 getElementsByTagName 和 childNodes 後返回的都是對象,所以它們後面必須使用 item(int),哪怕它們返回的'對象裏面只包含一個項目,也必須用item(0)來指定,否則就會出錯。

  用simplexml代碼實現:

$simxml = simplexml_load_file('./');

$t = $simxml->book;

$arr=array();

foreach ($t as $v){

if($v->author=='金庸'){

$arr[] = (string)$v->title;

}

}

print_r($arr);

使用 simplexml_load_file 後返回的是對象,該對象裏的項目既有對象又有數組,不管是對象還是數組,要循環裏面的內容都可以用 foreach。該實例最後獲取的內容 $v->title 其實是個對象,所以要用 string 轉化為字符串。

熱門標籤