• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

用户头像
it1352
帮助1

问题说明

有没有办法我可以使用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>

正确答案

#1

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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfkjkb
系列文章
更多 icon
同类精品
更多 icon
继续加载