Simplexml:通过 id 选择元素回显某个子元素

问题描述:

我需要一些关于 simplexml xpath 的建议.我的整个网站都有一个主 XML 文件,如下所示:

I'd need some advise with simplexml xpath. I have a master XML-file for my entire website like this:

<content>
<item id="001">
    <title>Video 1</title>
    <video>
        <file>video001.mp4</file>
        <dur>01:20</dur>
    </video>
</item>
<item id="2">
    <title>Video 2</title>
    <video>
        <file>video002.mp4</file>
        **<dur>03:53</dur>**
    </video>
</item>
</content>

现在我想回显 ID 为2"的项目视频的持续时间,即字符串03:53".

Now I want to echo the duration of the video of item with the id "2" which would be the string "03:53".

似乎是 simplexml 的简单用法,但大量教程仅涵盖循环和按数组编号进行选择.我想通过其 id 访问父元素并获取它的某个子元素的字符串.

Seems to be the simples use of simplexml, but the tons of tutorials out there only cover loops and selection by array number. I want to access a parent element by its id an grab the string of a certain child element of it.

提前致谢!符文

您可以为此目的使用 XPath:http://php.net/manual/en/simplexmlelement.xpath.php

You may use XPath for that purpose: http://php.net/manual/en/simplexmlelement.xpath.php

您的代码应该如下所示(或多或少):

You code should look like this (more or less):

$xml = simplexml_load_file('path/to/xml/file.xml');
$result = $xml->xpath('/content/item[@id=2]/video/dur/text()');
$result = $result[0];
echo $result;

这里是 phpFiddle http://phpfiddle.org/main/code/9hc-yqi一个>

Here is phpFiddle http://phpfiddle.org/main/code/9hc-yqi

可能您还应该将 xpath 结果投射到字符串上,但我不确定.我刚刚在 http://www.xpathtester.com/ 中测试了此代码的 xpath 部分,效果很好.

Probably you should also cast xpath result on string but I'm not sure. I just tested xpath part of this code inside http://www.xpathtester.com/ and it works just fine.