php - simplexml_load_file() 没有获取节点内容

标签 php xml simplexml

我无法使用 SimpleXML 库同时获取 XML 节点内容和属性:

我有以下 XML,想获取 content@name 属性和节点的内容:

<page id="id1">
    <content name="abc">def</content>
</page>

方法简单的xml_load_string()

print_r(simplexml_load_string('<page id="id1"><content name="abc">def</content></page>'));

输出这个:

SimpleXMLElement Object
(
   [@attributes] => Array
        (
            [id] => id1
        )

    [content] => def
)

如您所见,content 节点的内容存在,但缺少属性。如何接收内容和属性?

谢谢!

最佳答案

内容的属性存在。这只是 print_r() 的一个技巧,以及它如何处理内存中的 XML 对象。

$x = simplexml_load_string('<page id="id1"><content name="abc">def</content></page>');

print_r($x->content);
print_r($x->content['name']);
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [name] => abc
        )

    [0] => def
)

SimpleXMLElement Object
(
    [0] => abc
)

关于php - simplexml_load_file() 没有获取节点内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29799623/

相关文章:

安卓 "Valid XML document must have a root tag at line"

java - 如何将项目ID传递给另一个 Activity ?

PHP SimpleXML : How to access nested namespaces?

c# - 在 Silverlight (C#) 中访问 MySQL 数据库

php - 使用 PHP 将两个输入插入到 mySQL 中的一列中

xml - XSLT1.0 检查是否存在其祖先没有特定属性的后代,但如果有,则其值必须位于 RTF 变量中

PHP SimpleXML 获取文档节点

php - 如何从 PHP 中的 XML 文件中获取属性的值?

javascript - 在这种情况下,如何将数据从 html 传输到 php

php - 使用SQL检查数据库中是否存在用户