I have a link to the XML file.
I get it this way:
$xml = simplexml_load_file('http://example.com');
SimpleXMLElement {#1631 ▼
+"@attributes": array:1 [▶]
+"shop": SimpleXMLElement {#1605 ▼
+"name": "Site name"
+"company": "Thomas Munz"
+"url": "https://example.com"
+"currencies": SimpleXMLElement {#1606 ▶}
+"categories": SimpleXMLElement {#1607 ▶}
+"offers": SimpleXMLElement {#1608 ▼
+"offer": array:24403 [▶]
}
}
}
These XML files will change, as will the values in them. I cannot know the names of all elements in advance. So I want to get an array of all the elements in this XML file with their count. That is:
$array = [
'attributes' => '1',
'shop' => '1',
'name' => '1',
...
'offer' => '24403',
]
I really have no idea how to do this :c
Answering the question directly as it is currently stated:
To count all elements regardless of their nesting level, fetch all elements using the XPath expression
//*, then count them using a map, e.g.:For the following XML:
The PHP code above prints:
However, if nesting is important (e.g. the names of the tags may be equal at different levels) or a more sophisticated logic is needed, I'd recommend a recursive function similar to the following:
Another example of a recursive function: