用PHP进行XPath查询 [英] XPath query with PHP

查看:116
本文介绍了用PHP进行XPath查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的XML代码:

Here's the XML code I'm working with:

<inventory>
    <drink>
        <lemonade supplier="mother" id="1">
            <price>$2.50</price>
            <amount>20</amount>
        </lemonade>
        <lemonade supplier="mike" id="4">
            <price>$3.00</price>
            <amount>20</amount>
        </lemonade>
        <pop supplier="store" id="2">
            <price>$1.50</price>
            <amount>10</amount>
        </pop>
    </drink>
</inventory>

然后,我编写了一个简单的代码来练习使用XPath:

Then I wrote a simple code to practice working with XPath:

<?php
    $xmldoc = new DOMDocument();
    $xmldoc->load('sample.xml');

    $xpathvar = new Domxpath($xmldoc);

    $queryResult = $xpathvar->query('//lemonade/price');
    foreach($queryResult as $result) {
        echo $result->textContent;
    }
?>

该代码运行良好,可以按预期输出所有柠檬水价格值.现在,当我更改查询字符串以仅选择属性设置为某个值的元素时,例如

That code is working well, outputting all the lemonade price values as expected. Now when i change the query string to select only the elements with an attribute set to a certain value, like

//柠檬水[supplier ="mother"]/价格

//lemonade[supplier="mother"]/price

//lemonade [id ="1"]/价格

//lemonade[id="1"]/price

它不起作用,根本没有输出.我在做什么错了?

it won't work, no output at all. What am i doing wrong?

推荐答案

尝试一下:

//lemonade[@id="1"]/price

//lemonade[@supplier="mother"]/price

如果没有"@",它将查找具有该名称而不是属性的子元素.

Without the "@" it looks for child elements with that name instead of attributes.

这篇关于用PHP进行XPath查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆