从xml文件中选择所有人员=' Bob'

时间:2014-11-05 21:37:13

标签: php xml xpath

所以,当我使用php和MySQL时,我只是做了:

$result = $mysqli->query("SELECT * FROM table WHERE person='Bob'");

我现在正在使用PHP和XML,我知道如何做到这一点。我已经尝试使用谷歌搜索,但我不知道这将用XML调用。

我的XML是:

<People>
    <person>Bob</person>
    <about>Bob is a blob. He is 20 Years old, etc</about>
</People>
<People>
    <person>Jim</person>
    <about>Jim is 90 Years old, he plays basketball, etc</about>
</People>
<People>
    <person>Steve</person>
    <about>Steve is a superhero with the ability to fly.</about>
</People>

我基本上试图回应某个人的信息。因此,如果用户搜索Jim,它将回显:

Name: Jim
About: Jim is 90 Years old, he plays basketball, etc

1 个答案:

答案 0 :(得分:2)

使用XPath

XML:

<data>
    <People>
        <person>Bob</person>
        <about>Bob is a blob. He is 20 Years old, etc</about>
    </People>
    <People>
        <person>Jim</person>
        <about>Jim is 90 Years old, he plays basketball, etc</about>
    </People>
    <People>
        <person>Steve</person>
        <about>Steve is a superhero with the ability to fly.</about>
    </People>
</data>

PHP代码:

$xml = new SimpleXMLElement($xml_string);
$result = $xml->xpath('/data/People[person="Jim"]');
var_dump($result);

输出:

array(1) {
    [0]=>
        object(SimpleXMLElement)#2 (2) {
            ["person"]=>
                string(3) "Jim"
            ["about"]=>
                string(45) "Jim is 90 Years old, he plays basketball, etc"
        }
}