MacBook avec code sur un bureau

PHP et SimpleXML

Lorsque l’on veut traiter un fichier XML en PHP, il y a deux possibilités: soit l’on utilise SimpleXML, soit on passe par DOMDocument. Dans cet article je traiterai plus spécifiquement de SimpleXML.

Pour charger un fichier, il suffit d’utiliser la méthode simplexml_load_file

$xml = simplexml_load_file($file);

En faisant ainsi, vous récupérez un SimpleXMLElement.

Si le XML possède un namespace, il est impératif de l’ajouter à l’élément, sinon on ne pourra pas le parcourir.

 $xml->registerXPathNamespace('n', 'http://www.w3.org/TR/html4/'); 
<movies xmlns="http://www.w3.org/TR/html4/">
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El ActÓr</actor>
   </character>
  </characters>
  <plot>
   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.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>

Ensuite il est possible de récupérer les données voulues

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

on peut aussi, si voulu, utiliser xpath. Il est très important que chaque node ait le namespace, dans notre exemple « n »

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

Un très bon article se trouve sur php.net.