php simplexml根据字段的值获取特定项 [英] php simplexml get a specific item based on the value of a field

查看:142
本文介绍了php simplexml根据字段的值获取特定项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法我可以使用SimpleXML获得特定项目?

Is there a way i can get a specific item with SimpleXML ?

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

For example, i would like to get the title of an item having ID set to 12437 with this example 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>

推荐答案

这里有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.

这篇关于php simplexml根据字段的值获取特定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆