PHP XML:如何通过其兄弟姐妹获取 NodeValue?

发布于 2024-12-03 03:17:52 字数 649 浏览 0 评论 0原文

xml 示例:

<books>
  <book>
    <title>Hip Hop Hippo</title>
    <released>31-12-9999</released>
  </book>
  <book>
    <title>Bee In A Jar</title>
    <released>01-01-0001</released>
  </book>
</books>

我想要创建一个返回书名发布日期的函数。 例如:我想知道“Hip Hop Hippo”一书的发行日期。

我知道我可以使用 simplexml 并编写 ->book[0]->released。但这仅在我有静态 XML 并且我知道与“Hip Hop Hippo”匹配的 ->book[$i]->title 的位置时才有效。但在动态情况下则不然。我无法预测每一个变化,因为它来自 API 提供商。它可以是 book[1]book[2] 等。

我应该在我的函数中写什么?

Example of the xml:

<books>
  <book>
    <title>Hip Hop Hippo</title>
    <released>31-12-9999</released>
  </book>
  <book>
    <title>Bee In A Jar</title>
    <released>01-01-0001</released>
  </book>
</books>

I want to make a function that return the released date of a book title.
Ex: I want to get released date of the 'Hip Hop Hippo' book.

I know I can use simplexml and write ->book[0]->released. But that's only works when I have a static XML and I know where the ->book[$i]->title that match 'Hip Hop Hippo'. But not in dynamic case. I can't predict every changes, since it came from an API provider. It can be book[1], book[2], and so on.

What should I write in my function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

七堇年 2024-12-10 03:17:52

查看 xpath 函数 http://php.net/manual/en/simplexmlelement.xpath。然后

,您将能够编写如下查询:/books/book[title="Hip Hop Hippo"]

$string = <<<XML
<books>
  <book>
    <title>Hip Hop Hippo</title>
    <released>31-12-9999</released>
  </book>
  <book>
    <title>Hip Hop Hippo</title>
    <released>31-12-2000</released>
  </book>
  <book>
    <title>Bee In A Jar</title>
    <released>01-01-0001</released>
  </book>
</books>
XML;

$xml = new SimpleXMLElement($string);

$result = $xml->xpath('/books/book[title="Hip Hop Hippo"]');

foreach($result as $key=>$node)
{
  echo '<li>';
  echo $node->title . ' / ' . $node->released;
  echo '</li>';
}

Check out the xpath functions http://php.net/manual/en/simplexmlelement.xpath.php

You will then be able to write a query like: /books/book[title="Hip Hop Hippo"]

$string = <<<XML
<books>
  <book>
    <title>Hip Hop Hippo</title>
    <released>31-12-9999</released>
  </book>
  <book>
    <title>Hip Hop Hippo</title>
    <released>31-12-2000</released>
  </book>
  <book>
    <title>Bee In A Jar</title>
    <released>01-01-0001</released>
  </book>
</books>
XML;

$xml = new SimpleXMLElement($string);

$result = $xml->xpath('/books/book[title="Hip Hop Hippo"]');

foreach($result as $key=>$node)
{
  echo '<li>';
  echo $node->title . ' / ' . $node->released;
  echo '</li>';
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文