PHP parsing XML

What is the best way to parse an XML file in PHP?

First
Using the DOM Object

//code $dom = new DOMDocument(); $dom->load("xml.xml"); $root = $dom->getElementsByTagName("tag"); foreach($root as $tag) { $subChild = $root->getElementsByTagName("child"); // extract values and loop again if needed } 

Second
Using the simplexml_load Method

 // code $xml = simplexml_load_string("xml.xml"); $root = $xml->root; foreach($root as $tag) { $subChild = $tag->child; // extract values and loop again if needed } 

Note: These are the ones that I know of. If there is more filling.

You need to know which method is best suited for parsing large XML files, as well as which method is the fastest , regardless of how the method should be implemented

The size will vary from 500 KB to 2 MB. The parser should be able to parse both small and large files in minimal time with good memory usage, if possible.

+6
xml php parsing domdocument simplexml
source share
5 answers

I started using XMLReader to parse XML files. After you worked a little in search engines, he found that it was best to parse the XML files, since it does not load the entire XML file into memory. Say, if my XML files were 5 MB in size, and parsing it using XMLReader 5MB of my memory would not be lost.

 //usage $xml = new XMLReader(); $xml->XML($xmlString); while($xml->read) { if($xml->localName == 'Something') // check if tag name equals something { //do something } } 

Using the XML Reader, we can find out if the current tag is an opening tag or a closing tag and takes the necessary actions as necessary.

+4
source share

It depends on the document you are passing in, but XMLReader is usually faster than both simplexml and DOM ( http://blog.liip.ch/archive/2004/05/10/processing_large_xml_documents_with_php.html ). Personally, although I have never used XMLReader and usually decided to use it depending on whether I need to edit it:

  • simplexml if I just read a document
  • DOM if I change the DOM and save it

You can also convert objects between simplexml and DOM.

+4
source share

If you process huge files, they do not analyze them. Apply XSLT . This will save you a huge amount of memory and processing time.

+2
source share

I prefer simplexml_load_string for ease of use. Processing speed can greatly depend on the format of the XML file, if they use different methods of file analysis - try it in your files and see what is best for you.

+1
source share

Now all XML is processed by simpleXML in PHP when I develop. It is easily extensible and methods are rewritten if necessary.

+1
source share

All Articles