Search code examples
phpxmlsimplexml

count xml elements/nodes using SimpleXML


this could be duplicate, but I found nothing useful so far.

I'm trying to count nodes/childs of XML file using simplexml.

I've tried this.

$xml = simplexml_load_file("./file.xml");
echo count($xml->rss->channel->item);

and

echo count($xml->item);

but just outputting 0.

here is snapshot of XML

<?xml version="1.0"?>
<rss xmlns:xsd="http://www.w3.org/2001/XMLSchema"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:g="http://base.google.com/ns/1.0" version="2.0">
  <channel>
    <item>
      <title>PUDRA Pudra Ceket Ceket</title>
      <link>http://www.trendyol.com//Pudra-Ceket-IW6140005046/UrunDetay/31066/9188683?</link>
       <description>36 pudra pudra ceket ıw6140005046 ipekyol ceket kadın</description>
       <g:urunid>1423905</g:urunid>
       <g:id>1423905_14</g:id>
    </item>
    <item>
        ....
    </item>

Solution

  • This should work for you:

    echo count($xml->channel->item);
    

    EDIT:

    Why you have to it this way? Because form simplexml_load_file() you get a structure like this (print_r($xml);):

    SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [version] => 2.0
            )
    
        [channel] => SimpleXMLElement Object
            (
                [item] => Array
                    (
    

    Because of this structure you have to access the object like i said (above).