我使用simplexml_load_string将xml字符串转换为simpleXMLElement对象,其print_r输出值
SimpleXMLElement Object ( [message] => SimpleXMLElement Object ( [@attributes] => Array
( [to] => Danny [type] => greeting [id] => msg1 )
[body] => To be or not to be! ) [status] => SimpleXMLElement Object ( [@attributes] => Array ( [time] => 2015-01-12 ) [0] => SimpleXMLElement Object ( [@attributes] => Array ( [count] => 0 ) ) ))
如何从此对象中提取节点和属性值?运用
echo $xml->body
获取正文节点的内容不输出任何值
更新:
XML字符串
<start>
<message to="Danny" type="greeting" id="msg1 ">
<body>
To be or not to be!
</body>
</message>
<status time="2015-01-12">
<offline count="0"></offline>
</status>
</start>
想要提取节点值和属性
4 回答
假设
$string
在您的问题中保存xml字符串获取单个xml节点的值
会输出
从特定节点获取特定属性
会输出
PHP attributes() Function
在php.net上查找SimpleXMLElement文档:http://php.net/manual/en/class.simplexmlelement.php
这个类有一个方法列表,其中一个是属性,它返回所有元素属性:http://php.net/manual/en/simplexmlelement.attributes.php
我相信看看SimpleXML的基本用法也会有所帮助:http://php.net/manual/en/simplexml.examples-basic.php
最简单的解决方案是:
如果你想使用高级PHP功能,那么迭代器是不错的选择:
在上面的迭代器循环中,您可以使用节点和属性 .
你也可以在答案中提到@AlexAndrei的noe和属性值 .