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]
,依此类推。
我应该在我的功能中写什么?
答案 0 :(得分:3)
查看xpath函数http://php.net/manual/en/simplexmlelement.xpath.php
然后您就可以编写如下查询: / 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>';
}