【问题标题】:SELECT all from an xml file Where person='Bob'从 xml 文件中选择全部,其中 person='Bob'
【发布时间】:2014-11-05 21:37:12
【问题描述】:

所以,当我在 MySQL 中使用 php 时,我只是这样做了:

$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

【问题讨论】:

标签: php xml xpath


【解决方案1】:

使用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"
        }
}

【讨论】:

  • 你会如何用 css 设置它的样式并稍微清理一下,让它显示:Name: Jim About: Jim is 90 Years old, he plays basketball, etc
  • 与 MySQL 的结果相同
  • 对于 MySQL,我使用了一个 Div。那么,我会对 XML 做同样的事情吗
  • 使用上面的代码解析 XML 并将其存储在 PHP 变量中。所以你可以echo 正常的值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多