XML Xpath用法

时间:2013-05-01 17:08:27

标签: php xpath

orn​​ek.xml:

<?xml version="1.0" encoding="UTF-8"?>
<library>
    <book onay="e" katid="31" dil="tr">
        <kitapadi>Dear Lovely</kitapadi>
        <yazar>Author 1234</yazar>
        <isbn>1234513</isbn>
         </book>
         <book onay="e" katid="32" dil="en">
        <kitapadi>Love and Hate</kitapadi>
        <yazar>Author 345</yazar>
        <isbn>1234513</isbn>
         </book>
</library>

PHP代码:

$xml = simplexml_load_file('veri/ornek.xml');
$search= '34';
$result = $xml->xpath('//yazar[contains(.,"'.$search.'")]');
foreach($result as $tt){
    echo $tt;
    }

如果我使用它,我可以获得yazar属性。但我想得到另一个属性 例如:

$ search = 34匹配yazar 34在kitapadi中提供此区块,isbn,yazar

2 个答案:

答案 0 :(得分:0)

这个XPath查询可以解决问题:

//*[text()[contains(., '34')]]

结果:

Element='<yazar>Author 1234</yazar>'
Element='<isbn>1234513</isbn>'
Element='<yazar>Author 345</yazar>'
Element='<isbn>1234513</isbn>'

答案 1 :(得分:0)

如果你想在yazar中获得包含搜索字符串的书。使用这样的东西:

$xml = simplexml_load_file('veri/ornek.xml');
$search= "34";
$result = $xml->xpath("//book[yazar[contains(.,' $search')]]");
foreach($result as $tt){
    echo $tt->isbn;
    }