php simplexml根据字段的值获取特定项

有没有办法用SimpleXML获取特定项目?

例如,我想通过此示例xml获取ID设置为12437的项目的标题:

<items>
  <item>
    <title>blah blah 43534</title>
    <id>43534</id>
  </item>
  <item>
    <title>blah blah 12437</title>
    <id>12437</id>
  </item>
  <item>
    <title>blah blah 7868</title>
    <id>7868</id>
  </item>
</items>

解决方法:

这里有两种简单的方法可以做你想要的,一种是对每个项目进行迭代,如下所示:

<?php
$str = <<<XML
<items>
<item>
<title>blah blah 43534</title>
<id>43534</id>
</item>
<item>
<title>blah blah 12437</title>
<id>12437</id>
</item>
<item>
<title>blah blah 7868</title>
<id>7868</id>
</item>
</items>
XML;

$data = new SimpleXMLElement($str);
foreach ($data->item as $item)
{
    if ($item->id == 12437)
    {
        echo "ID: " . $item->id . "\n";
        echo "Title: " . $item->title . "\n";
    }
}

Live DEMO.

另一个是使用XPath,以指向您想要的确切数据,如下所示:

<?php
$str = <<<XML
<items>
<item>
<title>blah blah 43534</title>
<id>43534</id>
</item>
<item>
<title>blah blah 12437</title>
<id>12437</id>
</item>
<item>
<title>blah blah 7868</title>
<id>7868</id>
</item>
</items>
XML;

$data = new SimpleXMLElement($str);
// Here we find the element id = 12437 and get it's parent
$nodes = $data->xpath('//items/item/id[.="12437"]/parent::*');
$result = $nodes[0];
echo "ID: " . $result->id . "\n";
echo "Title: " . $result->title . "\n";

Live DEMO.

上一篇:JDOM生成xml文档


下一篇:php – preg_match(); – 未知修饰符”