PHP SimpleXML - Récupérer
PHP SimpleXML - Récupération des valeurs de nœuds et d’attributs
Section titled “PHP SimpleXML - Récupération des valeurs de nœuds et d’attributs”SimpleXML est une extension PHP intégrée qui offre un moyen intuitif d’analyser et de manipuler les données XML. Elle représente un document XML comme un objet, ce qui rend l’accès aux données direct.
Bien que SimpleXML soit pratique pour les tâches XML de base, pour des manipulations complexes ou des fichiers très volumineux, envisagez d’utiliser les extensions DOMDocument ou XMLReader.
PHP SimpleXML - Obtenir les valeurs des nœuds
Section titled “PHP SimpleXML - Obtenir les valeurs des nœuds”Pour lire un fichier XML, utilisez la fonction simplexml_load_file(). Elle renvoie un objet SimpleXMLElement en cas de succès, ou false en cas d’échec. Vérifiez toujours la valeur de retour avant de continuer.
Considérez ce fichier XML simple, note.xml :
<?xml version="1.0" encoding="UTF-8"?><note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body></note>Voici comment obtenir les valeurs des nœuds de note.xml :
<?phpdeclare(strict_types=1);
$xmlFilePath = "note.xml";
if (!file_exists($xmlFilePath)) { echo "Error: File not found ({$xmlFilePath})"; exit;}
// Charger le fichier XML$xml = simplexml_load_file($xmlFilePath);
// Vérifier si le chargement a réussiif ($xml === false) { echo "Error: Cannot create SimpleXMLElement object."; // Vous voudrez peut-être enregistrer les erreurs XML spécifiques ici en utilisant libxml_get_errors() // libxml_use_internal_errors(true); // $xml = simplexml_load_file(...); // if ($xml === false) { foreach(libxml_get_errors() as $error) { echo $error->message; } } exit;}
// Accéder aux valeurs des nœuds comme propriétés d'objet// Le transtypage en chaîne est souvent implicite mais bon pour la clartéecho (string)$xml->to . "<br>";echo (string)$xml->from . "<br>";echo (string)$xml->heading . "<br>";echo (string)$xml->body;?>La sortie attendue du code ci-dessus est :
Tove<br>Jani<br>Reminder<br>Don't forget me this weekend!Travailler avec un fichier XML plus complexe
Section titled “Travailler avec un fichier XML plus complexe”Utilisons un fichier XML plus complexe, books.xml, pour d’autres exemples :
<?xml version="1.0" encoding="UTF-8"?><bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J. K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="WEB"> <title lang="en-us">XQuery Kick Start</title> <author>James McGovern</author> <year>2003</year> <price>49.99</price> </book> <book category="WEB"> <title lang="en-us">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book></bookstore>PHP SimpleXML - Accéder à des éléments spécifiques
Section titled “PHP SimpleXML - Accéder à des éléments spécifiques”Lorsque plusieurs éléments partagent le même nom (comme <book>), SimpleXML les traite comme une collection itérable accessible via une notation d’index de type tableau.
Cet exemple récupère le <title> du premier (index 0) et du second (index 1) élément <book> :
<?phpdeclare(strict_types=1);
$xmlFilePath = "books.xml";
if (!file_exists($xmlFilePath)) { die("Error: File not found ({$xmlFilePath})");}
$xml = simplexml_load_file($xmlFilePath);
if ($xml === false) { die("Error: Cannot create object");}
// Vérifier si les éléments de livre existent avant d'y accéderif (isset($xml->book[0])) { echo (string)$xml->book[0]->title . "<br>";}if (isset($xml->book[1])) { echo (string)$xml->book[1]->title;}?>La sortie attendue est :
Everyday Italian<br>Harry PotterPHP SimpleXML - Parcourir les nœuds
Section titled “PHP SimpleXML - Parcourir les nœuds”Vous pouvez facilement itérer sur des éléments ayant le même nom en utilisant une boucle foreach. La méthode children() peut être utilisée, mais souvent, l’itération directe sur la propriété parente fonctionne.
Cet exemple parcourt tous les éléments <book> et affiche leurs détails :
<?phpdeclare(strict_types=1);
$xmlFilePath = "books.xml";
if (!file_exists($xmlFilePath)) { die("Error: File not found ({$xmlFilePath})");}
$xml = simplexml_load_file($xmlFilePath);
if ($xml === false) { die("Error: Cannot create object");}
// Itérer directement sur les éléments <book>foreach ($xml->book as $book) { echo htmlspecialchars((string)$book->title, ENT_QUOTES, 'UTF-8') . ", "; echo htmlspecialchars((string)$book->author, ENT_QUOTES, 'UTF-8') . ", "; echo htmlspecialchars((string)$book->year, ENT_QUOTES, 'UTF-8') . ", "; echo htmlspecialchars((string)$book->price, ENT_QUOTES, 'UTF-8') . "<br>";}?>Remarque : Nous utilisons htmlspecialchars() ici pour afficher en toute sécurité le contenu textuel dans un contexte HTML, empêchant ainsi les potentielles vulnérabilités de Cross-Site Scripting (XSS) si les données XML provenaient d’une source non fiable.
La sortie attendue est :
Everyday Italian, Giada De Laurentiis, 2005, 30.00<br>Harry Potter, J. K. Rowling, 2005, 29.99<br>XQuery Kick Start, James McGovern, 2003, 49.99<br>Learning XML, Erik T. Ray, 2003, 39.95<br>PHP SimpleXML - Obtenir les valeurs d’attributs
Section titled “PHP SimpleXML - Obtenir les valeurs d’attributs”Les attributs sont accessibles en utilisant une notation de type tableau sur l’objet élément.
Cet exemple récupère l’attribut category du premier <book> et l’attribut lang de l’élément <title> à l’intérieur du second <book> :
<?phpdeclare(strict_types=1);
$xmlFilePath = "books.xml";
if (!file_exists($xmlFilePath)) { die("Error: File not found ({$xmlFilePath})");}
$xml = simplexml_load_file($xmlFilePath);
if ($xml === false) { die("Error: Cannot create object");}
// Accéder aux attributs en utilisant la notation de tableauif (isset($xml->book[0]['category'])) { echo (string)$xml->book[0]['category'] . "<br>";}
if (isset($xml->book[1]->title['lang'])) { echo (string)$xml->book[1]->title['lang'];}?>La sortie attendue est :
COOKING<br>enPHP SimpleXML - Parcourir les attributs
Section titled “PHP SimpleXML - Parcourir les attributs”Vous pouvez combiner l’itération à travers les éléments et l’accès à leurs attributs.
Cet exemple récupère l’attribut lang de l’élément <title> de chaque <book> :
<?phpdeclare(strict_types=1);
$xmlFilePath = "books.xml";
if (!file_exists($xmlFilePath)) { die("Error: File not found ({$xmlFilePath})");}
$xml = simplexml_load_file($xmlFilePath);
if ($xml === false) { die("Error: Cannot create object");}
foreach ($xml->book as $book) { // Vérifier si l'attribut lang existe avant d'y accéder if (isset($book->title['lang'])) { echo htmlspecialchars((string)$book->title['lang'], ENT_QUOTES, 'UTF-8'); } else { echo "(no lang attribute)"; // Gérer les cas où l'attribut pourrait être manquant } echo "<br>";}?>La sortie attendue est :
en<br>en<br>en-us<br>en-us<br>Pour aller plus loin
Section titled “Pour aller plus loin”Pour des détails complets sur les fonctions SimpleXML et leur utilisation, consultez le manuel officiel de PHP : https://www.php.net/manual/en/book.simplexml.php