Code sur écran d'ordinateur

PHP and SimpleXML

When you want to process an XML file in PHP, there are two possibilities: either we use SimpleXML or we go through DOMDocument. In this article I will deal more specifically with SimpleXML.

To load a file, just use the simplexml_load_file method

$xml = simplexml_load_file($file);

By doing so, you get a SimpleXMLElement.

If the XML has a namespace, it is imperative to add it to the element, otherwise you won’t be able to browse it.

 $xml->registerXPathNamespace('n', 'http://www.w3.org/TR/html4/'); 

 
  PHP: Behind the Parser
  
   
    Ms. Coder
    Onlivia Actora
   
   
    Mr. Coder
    El ActÓr
   
  
  
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  
  
   PHP solves all my web problems
  
  7
  5
 

Then it is possible to retrieve the desired data

echo $movies->movie[0]->plot;

we can also, if desired, use xpath. It is very important that each node has the namespace, in our example “n”

echo $xml->xpath('//n:movie/n:plot')

A very good article can be found on php.net.