Getting element names/values with XML/Xpath/PHP

DaOgre picture DaOgre · Jan 24, 2011 · Viewed 9.5k times · Source

I have an XML schema that looks as follows:

<xml>
  <user id="1">
    <first_name>Bill</first_name>
    <last_name>Steve</last_name>
    <phone_numbers>
      <work>xxx-xxx-xxxx</work>
      <home>xxx-xxx-xxxx</home>
    </phone_numbers>
   </user>
   <user id="2">
      ........
   </user>
</xml>

Im working on parsing all of this information into PHP using DOM. Ex.

$userInfo = $doc->getElementsByTagName( "user" ); 
foreach($userInfo as $row)
{
       $first_name = $row->getElementsByTagName("first_name");
}

When I try to nest this to select the phone numbers however I get an error. I've tried using XPath to select the phone numbers with equal problems. I tried something along the lines of

$userInfo = $doc->getElementsByTagName( "user" ); 
foreach($userInfo as $row)
{
       $phoneInfo = $row->getElementsByTagName("phone_numbers");
       foreach($phoneInfo as $row2)
       {
            $work = $row2->getElementsByTagName("work");
       }
}

Im curious if Im doing something fundamentally wrong, or how to get this going. I've been tearing my hair out for a few hours now.

Answer

Mathias E. picture Mathias E. · Jan 24, 2011

You can't get the value directly from a DOMNodeList Object, try this :

$userInfo = $doc->getElementsByTagName( "user" ); 
foreach($userInfo as $row)
{
       $phoneInfo = $row->getElementsByTagName("phone_numbers");
       foreach($phoneInfo as $row2)
       {
            // get the value from the first child
            $work = $row2->getElementsByTagName("work")->item(0)->nodeValue;
            $home = $row2->getElementsByTagName("home")->item(0)->nodeValue;
       }
}