如果在php中使用了另一个标签,如何读取xml标签?

时间:2018-09-27 12:50:23

标签: php xml zend-framework

我正在尝试读取xml标签,但是有一个问题,如果标签内有另一个标签,我只会得到它的属性。

示例: 我有一个xml文件

    $myXMLData =
    "<?xml version='1.0' encoding='UTF-8'?>
<note>
<to><hello role='admin'/>Hello World</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";
$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");
echo "<pre>";
print_r($xml);

输出:

    SimpleXMLElement Object
(
    [to] => SimpleXMLElement Object
        (
            [hello] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [role] => admin
                        )

                )

        )

    [from] => Jani
    [heading] => Reminder
    [body] => Don't forget me this weekend!
)

但是我想要标题“ Hello World”。有人可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您无法将SimpleXML元素的值作为对象获取,而必须将其强制转换为字符串(或int或...):

$myXMLData = "<title><anchor id='page1' role='first'/>Xyz Title</title>";
$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");
echo "<pre>";
echo (string)$xml;

输出:

Xyz Title

对于您的修订问题,只是

echo (string)$xml->to;

输出:

Hello world