Search code examples
phpsimplexml

How to get the specific inner node with SimpleXml?


my xml is structured as follow:

<?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>

I made this code that iterate through all xml node:

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();
     }
   }
}

what I'm trying to achieve is that when $node is equal to:

jfhsjfhksdjfhsjkfhksjfsdk

the connection node is returned as array, how I can achieve this?


Solution

  • If the XML you're trying to parse is what you've posted here, it's invalid since

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

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

    (and yours doesn't, and parsing such string fails with Exception: String could not be parsed as XML in ...).

    So your XML should be:

    <?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>
    

    And you don't need to iterate through the collection

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