0
我想用php SimpleXML和xpath解析XML文件,並且遇到問題,獲取路徑並訪問屬性值。任何幫助讚賞。用php和xpath解析xml - 獲取路徑right
這裏是我的xml文件: -
<message:MessageGroup xmlns="http://mynamespace.com">
<Book>
<BookKey>
<Value concept="TITLE" value="Gone Girl"/>
<Value concept="AUTHOR" value="Gillian Flynn"/>
</BookKey>
<Sales>
<Month>Jan</Month>
<Number value="20"/>
</Sales>
<Sales>
<Month>Feb</Month>
<Number value="15"/>
</Sales>
<Sales>
<Month>Mar</Month>
<Number value="30"/>
</Sales>
</Book>
<Book>
<BookKey>
<Value concept="TITLE" value="Inferno"/>
<Value concept="AUTHOR" value="Dan Brown"/>
</BookKey>
<Sales>
<Month>Jan</Month>
<Number value="10"/>
</Sales>
<Sales>
<Month>Feb</Month>
<Number value="15"/>
</Sales>
<Sales>
<Month>Mar</Month>
<Number value="3"/>
</Sales>
</Book>
</message:MessageGroup>
我需要解析此得到以下的輸出: -
Gone Girl,Gillian Flynn,Jan,20
Gone Girl,Gillian Flynn,Feb,15
Gone Girl,Gillian Flynn,Mar30
Inferno,Dan Brown,Jan,10
Inferno,Dan Brown,Feb,15
Inferno,Dan Brown,Mar,3
我寫了下面的代碼: -
<?php
$xmlfile = 'Books.xml';
$xml = simplexml_load_file($xmlfile);
$namespace = 'http://mynamespace.com';
$xml->registerXPathNamespace('ns',$namespace);
$books = $xml->xpath('//ns:Book');
//loop through each book -
foreach($books as $book) {
$values = $xml->xpath('ns:BookKey/Value');
$bookkeys= array();
//loop through each Book's BookKey Values and push them to array -
foreach($values as $value){
array_push($bookkeys, $value->attributes()->value);
}
$sales = $xml->xpath('ns:Sales');
//loop through each Book's Sales and write out Month and Number value after the book key values -
foreach($sales as $sale){
foreach($bookkeys as $bk){
echo $bk.",";
}
echo $sale->Month;
echo ",";
echo $sale->Number->attributes()->value;
echo "\n";
}
}
?>
從var_dump中,$ books數組看起來沒問題;儘管$ values和$ sales是空數組,但顯然路徑並不正確。我已經嘗試刪除名稱空間,但仍然得到一個空數組;我想避免將文件中的所有值和銷售情況拉出來,而不是僅僅針對每本特定的書。
「消息」的xmlns在哪裏? – 2013-04-26 16:35:14
標準迭代器僅用於默認名稱空間中的子節點。您可能正在使用命名空間參數集來查找['SimpleXMLElement :: children()'](http://php.net/SimpleXMLElement.children)。同樣適用於['SimpleXMLElement :: attributes()'](http://php.net/SimpleXMLElement.attributes),您還需要傳遞名稱空間,它不會從元素節點繼承。 – hakre 2013-04-27 06:41:25