Search code examples
phpsimplexmllowercase

PHP simplexml children to lowercase


I've got this as XML:

...
<product>
<id>1</id>
<defaultImage>test.jpg</defaultImage>
</product>
...

I've got this as php:

$testcase = 'defaultimage';
$xml = simplexml_load_file('./temp/'.$i.'.xml');
foreach ($xml->children() as $child) {
    $child->$testcase;
}

Now the problem is this, I'm forced to have $testcase in a lowercase form (defaultimage) BUT in the XML file the name of the child is: defaultImage (note the uppercase I)

Question: How can I handle all the children as lowercases?


Solution

  • You can use the ->getName() method to find out the name of a node while looping through an inner ->children() array.

    For clarity, I've used a more explicit loop over all product nodes for the outer loop

    $testcase = 'defaultimage';
    $xml = simplexml_load_file('./temp/'.$i.'.xml');
    foreach ( $xml->product as $product )
    {
       foreach ( $product->children as $child )
       {
          if ( strtolower($child->getName()) == $testcase )
          {
             // Do whatever it is you need to do with the <defaultImage> node
          }
       }
    }