2011-12-07 87 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”)