如何用SimpleXml获取具体的内部节点?

How to get the specific inner node with SimpleXml?

我的 xml 结构如下:

<?xml version="1.0" ?>
<user>
    <name>
        foo
    </name>
    <token>
        jfhsjfhksdjfhsjkfhksjfsdk
    </token>
    <connection>
        <host>
            localhost
        </host>
        <username>
            root
        </username>
        <dbName>
            Test
        </dbName>
        <dbPass>
            123456789
        </dbPass>
    </connection>
</user>
<user>
    ... same structure...
</user>

我编写了遍历所有 xml 节点的代码:

function getConString($node)
{
   $item = file_get_contents($_SERVER['DOCUMENT_ROOT'] . "con");
   $nodes = new SimpleXMLElement($item);
   $result = $nodes[0];

   foreach($result as $item => $value)
   {
      if($item == "token")
      {
         return $value->__toString();
     }
   }
}

我想要实现的是,当 $node 等于:

jfhsjfhksdjfhsjkfhksjfsdk

connection 节点作为数组返回,我该如何实现?

如果您尝试解析的 XML 是您在此处发布的内容,则它无效,因为

XML documents must contain one root element that is the parent of all other elements:

http://www.w3schools.com/xml/xml_syntax.asp

(而你的没有,并且解析此类字符串失败 Exception: String could not be parsed as XML in ...)。

所以你的 XML 应该是:

<?xml version="1.0" ?>
<users>
    <user>
        <name>
            foo
        </name>
        <token>
            jfhsjfhksdjfhsjkfhksjfsdk
        </token>
        <connection>
            <host>
                localhost
            </host>
            <username>
                root
            </username>
            <dbName>
                Test
            </dbName>
            <dbPass>
                123456789
            </dbPass>
        </connection>
    </user>
    <user>
        ... same structure...
    </user>
</users>

而且您不需要遍历集合

// $nodes is SimpleXMLElement
$user = $nodes->user[0];
if($user->token)
   return $user->token->__toString();