2011-12-07 85 views
0

我有以下xml,我想篩選以僅顯示指定發佈者的數據。xml to php with filter

<?xml version="1.0"?> 
<books> 
    <book isbn="978-1594489501"> 
    <title>A Thousand Splendid Suns</title> 
    <author>Khaled Hosseini</author> 
    <publisher>Riverhead Hardcover</publisher> 
    <amazon_price>14.27</amazon_price> 
    </book> 
    <book isbn="978-1594489587"> 
    <title>The Brief Wondrous Life of Oscar Wao</title> 
    <author>Junot Diaz</author> 
    <publisher>AB</publisher> 
    <amazon_price>14.97</amazon_price> 
    </book> 
    <book isbn="978-0545010221"> 
    <title>Harry Potter and the Deathly Hallows</title> 
    <author>J. K. Rowling</author> 
    <publisher>AB</publisher> 
    <amazon_price>19.24</amazon_price> 
    </book> 
</books> 

我希望把HTML表從示例發佈AB的數據。

<?php 
// load SimpleXML 
$books = new SimpleXMLElement("books.xml); 
$myVar="AB"; 
$books = $s->xpath("//book"); 
echo <<<EOF 
<table style='width: 99%;'> 
     <thead> 
<tr> 

       <th>Title</th> 
       <th>Author</th> 


     </tr> 
</thead> 

EOF; 
foreach($books as $book) // loop through our books 
{ 
      //if the type of $product books user input (ie $myVar) 
     if ($book->type == $myVar) 
     { 



     echo <<<EOF 
     <tbody> 
     <tr> 

       <td>{$book->title} </td> 
       <td>{$book->author}</td> 


     </tr> 


EOF; 
}} 
echo '</tbody>'; 
echo '</table>'; 
?> 

我是一個非對象在得到調用一個成員函數的XPath(),任何幫助,請。

+0

變量$ s是字符串'$書= $ S->的XPath( 「//書」)中未定義;' – Minras

回答

2

來自文件的數據通過the constructor of SimpleXMLElement您必須將第三個參數設置爲true。否則,你傳遞作爲第一個參數的字符串被解釋爲 「原始」 的XML數據,即要麼

$x = new SimpleXMLELement('<books><book>....</books>'); 

$x = new SimpleXMLELement('books.xml', 0, true); 

$x = simplexml_load_file('books.xml'); 

並有一些代碼中的其他錯誤。例如。您想要測試<publisher>元素中的特定值,但是您正在測試if ($book->type == $myVar)
這也可能是在這種情況下,更好地把病情進入XPath表達式

<?php 
$doc = new SimpleXMLElement("books.xml", 0, true); 
$myVar="AB"; 
$books = $doc->xpath("//book[publisher='$myVar']"); 
... 
+0

感謝volkerk它的工作 – meandme

+0

+1啊,很好。 – Wiseguy

1

你叫$s->xpath("//book"),但它似乎不存在$s存在。我想你的意思是這條線上面:

$s = new SimpleXMLElement("books.xml"); 

代替

$books = new SimpleXMLElement("books.xml"); 

,如果你想加載不要忘了關閉的引號"(把 「books.xml」)