且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-23 08:40:32

这里有2种简单的方式来做您想要的事情,一种是像这样对每个项目进行迭代:

Here are 2 simple ways of doing what you want, one is iterating with each item like this:

<?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来精确定位所需的数据,如下所示:

The other would be using an XPath, to pin point the exact data you want like this:

<?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.