返回基于URL参数的特定XML节点

时间:2017-05-05 09:18:44

标签: php xml

希望我正确地问这个问题,因为我猜这需要PHP来实现。

我想要做的是通过URL返回特定节点和XML数据的所有子节点。

示例:mydomain.com/myphpfile.php?book_id=1&title="My书名“

因此,通过显示上面的URL将仅返回以下xml数据

   <Books>
     <book id="1">
        <title>My Book Title</title>
        <author>John Doe</author>
        <genre>Horror</genre>
       <description>Some long text description</description>
     </book>
  </Books>

这只是XML的一个例子:

 <Books>
     <book id="1">
        <title>My Book Title</title>
        <author>John Doe</author>
        <genre>Horror</genre>
       <description>Some long text description</description>
     </book>

       <book id="2">
        <title>My Book Title</title>
        <author>John Doe</author>
        <genre>Comedy</genre>
        <description>Some long text description</description>  
     </book>

       etc
 </Books>

1 个答案:

答案 0 :(得分:1)

 $book_id = 1;
 $title = 'My Book Title';

 $xml = simplexml_load_string($str);
 // find not suitable items - having incorrect id  or title
 $dels = $xml->xpath('//book[@id != '. $book_id .' or title != "'. $title .'"]');
  // delete found books from xml
  foreach($dels as $node) {
     unset($node->{0});
  }

echo  $xml->saveXML();