简体   繁体   English

如何使用php的SimpleXML获取XML的第一个标记的名称?

[英]How to get name of very first tag of XML with php's SimpleXML?

I am parsing XML strings using simplexml_load_string() , but I noticed that i don't get the name of the very first tag. 我正在使用simplexml_load_string()解析XML字符串,但我注意到我没有得到第一个标记的名称。

For example, I have these two xml strings: 例如,我有这两个xml字符串:

$s = '<?xml version="1.0" encoding="UTF-8"?>
<ParentTypeABC>
    <chidren1>
        <children2>1000</children2>
    </chidren1>
</ParentTypeABC>
';

$t = '<?xml version="1.0" encoding="UTF-8"?>
<ParentTypeDEF>
    <chidren1>
        <children2>1000</children2>
    </chidren1>
</ParentTypeDEF>
';

NOTICE that they are nearly identical, the only difference being that one has the first node as <ParentTypeABC> and the other as <ParentTypeDEF> 注意它们几乎相同,唯一的区别是第一个节点为<ParentTypeABC>而另一个节点为<ParentTypeDEF>

then I just convert them to SimpleXML objects: 然后我只是将它们转换为SimpleXML对象:

$o = simplexml_load_string($s);
$p = simplexml_load_string($t);

but then i have two equal objects, none of them having the "top" node's name appearing, either ParentTypeABC or ParentTypeDEF (I examine the objects using print_r() ): 但后来我有两个相同的对象,它们都没有出现“顶部”节点的名称,无论是ParentTypeABC还是ParentTypeDEF (我使用print_r()检查对象):

// with top node "ParentTypeABC"
SimpleXMLElement Object
(
    [chidren1] => SimpleXMLElement Object
        (
            [children2] => 1000
        )

)
// with top node "ParentTypeDEF"
SimpleXMLElement Object
(
    [chidren1] => SimpleXMLElement Object
        (
            [children2] => 1000
        )

)

So how I am supposed to know the top node's name? 那我怎么知道顶级节点的名字呢? If I parse unknown XMLs and I need to know what's the top node name, what can I do? 如果我解析未知的XML并且我需要知道什么是顶级节点名称,我该怎么办?

Is there an option in simplexml_load_string() I could use? 我可以使用simplexml_load_string()的选项吗?

I know there are MANY ways to parse XML's with PHP, but I'd like it to be as simple as posible, and to get a simple object or array I could navigate easily. 我知道有很多方法可以用PHP解析XML,但是我希望它像posible一样简单,并且为了获得一个简单的对象或数组,我可以轻松导航。

I made a simple example here to fiddle with. 我在这里做了一个简单的例子。

SimpleXML has a getName() method. SimpleXML有一个getName()方法。

echo $xml->getName();

This should return the name of the respective node, no matter if root or not. 这应该返回相应节点的名称,无论是否为root。

http://php.net/manual/en/simplexmlelement.getname.php http://php.net/manual/en/simplexmlelement.getname.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM