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

时间:2013-07-09 00:04:50

标签: php xml rss 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>

2 个答案:

答案 0 :(得分:7)

以下是两种简单的方法,可以按照以下方式对每个项目进行迭代:

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

答案 1 :(得分:3)

您想要使用Xpath。它与SimpleXML: Selecting Elements Which Have A Certain Attribute Value中概述的基本完全相同,但在您的情况下,您不是决定属性值而是决定元素值。

然而,在Xpath中,您正在寻找的元素都是父元素。因此,制定xpath表达式非常简单:

// Here we find the item element that has the child <id> element
//   with node-value "12437".

list($result) = $data->xpath('(//items/item[id = "12437"])[1]');
$result->asXML('php://output');

输出(美化):

<item>
  <title>title of 12437</title>
  <id>12437</id>
</item>

让我们再次看到这个xpath查询的核心:

//items/item[id = "12437"]

它写成:选择所有<item>个元素,这些元素属于任何<items>个元素,这些元素本身都有一个名为<id>的子元素,其值为"12437"

现在有了缺少的东西:

(//items/item[id = "12437"])[1]

左右括号表示:从所有这些<item>元素中,仅选择第一个元素。根据您的结构,这可能是必要的,也可能不是必需的。

所以这是完整的用法示例和online demo

<?php
/**
 * php simplexml get a specific item based on the value of a field
 * @lin https://stackoverflow.com/q/17537909/367456
 */
$str = <<<XML
<items>
  <item>
    <title>title of 43534</title>
    <id>43534</id>
  </item>
  <item>
    <title>title of 12437</title>
    <id>12437</id>
  </item>
  <item>
    <title>title of 7868</title>
    <id>7868</id>
  </item>
</items>
XML;

$data = new SimpleXMLElement($str);

// Here we find the item element that has the child <id> element
//   with node-value "12437".

list($result) = $data->xpath('(//items/item[id = "12437"])[1]');
$result->asXML('php://output');

所以你在问题标题中称之为字段的是一本儿童元素。在搜索更复杂的xpath查询时,请记住这一点,以便找到您想要的内容。