Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count xml elements/nodes using SimpleXML

Tags:

php

xml

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>
like image 630
Mubin Avatar asked Oct 19 '25 04:10

Mubin


1 Answers

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).

like image 135
Rizier123 Avatar answered Oct 20 '25 19:10

Rizier123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!