The following php script gives count of elements in a single xml file in the folder uploads. But I have number of xml files in the folder. What to modify in the following script so that I get result in tabular format with the file name and element count for all the xml files in the folder.
<?php
$doc = new DOMDocument;
$xml = simplexml_load_file("uploads/test.xml");
//file to SimpleXMLElement
$xml = simplexml_import_dom($xml);
print("Number of elements: ".$xml->count());
?>
2
Answers
First, create a
function
with the logic you have:Note that I:
This is how you can get the files of a given path:
we get all files except for
.
and..
, which are surely not of interest here. Read more about scandir here: https://www.php.net/manual/en/function.scandir.phpYou received an array of filenames on success, so, let’s loop it and perform the logic you need:
EDIT
As @Juan kindly explained in the comment section, one can use
instead of
scandir
and that would ensure that we no longer need a call forarray_diff
and later we can avoid theif
inside the loop:You’re first loading the XML file into a
SimpleXMLElement
then import it into aDOMElement
and call the methodcount()
on it. This method does not exists onDOMElement
– only onSimpleXMLElement
. So the import would not be necessary.You can use a
GlobIterator
to iterate the files:With DOM you can use Xpath to fetch specific values from the XML.
The Xpath Expression
/*
/*/*
count(/*/*)
*
is an universal selector for any element node. If you can you should be more specific and use the actual element names (e.g./list/item
).