simplexml,返回具有相同标签的多个项目 [英] simplexml, returning multiple items with the same tag

查看:33
本文介绍了simplexml,返回具有相同标签的多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将以下 XML 文件加载到 php simplexml 中.

I have the following XML file loaded into php simplexml.

<adf>
<prospect>
<customer>
<name part="first">Bob</name>
<name part="last">Smith</name>
</customer>
</prospect>
</adf>

使用

$customers = new SimpleXMLElement($xmlstring); 

这将返回Bob"但我如何返回姓氏?

This will return "Bob" but how do I return the last name?

echo $customers->prospect[0]->customer->contact->name;

推荐答案

您可以使用数组样式的语法,按编号访问不同的 元素.

You can access the different <name> elements by number, using array-style syntax.

$names = $customers->prospect[0]->customer->name;

echo $names[0]; // Bob
echo $names[1]; // Smith

事实上,您已经<prospect>元素做的!

In fact, you're already doing it for the <prospect> element!

另请参阅手册中的SimpleXML 基本用法.

See also Basic SimpleXML Usage in the manual.

如果您想根据某些条件选择元素,则 XPath 是使用的工具.

If you want to select elements based on some criteria, then XPath is the tool to use.

$customer   = $customers->prospect[0]->customer;
$last_names = $customer->xpath('name[@part="last"]'); // always returns an array
echo $last_names[0]; // Smith

这篇关于simplexml,返回具有相同标签的多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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