Fonction PHP simplexml_load_string()
Exemple
Convertissez une chaîne XML en objet, puis affichez les clés et les éléments de l'objet :
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Do not forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
print_r($xml);
?>
Définition et utilisation
La fonction simplexml_load_string() convertit une chaîne XML bien formée en un objet.
Syntaxe
simplexml_load_string(data, class, options, ns, is_prefix)
Valeurs des paramètres
Parameter | Description |
---|---|
data | Required. Specifies a well-formed XML string |
class | Optional. Specifies the class of the new object |
options | Optional. Specifies additional Libxml parameters. Is set by specifying the option and 1 or 0 (TRUE or FALSE, e.g. LIBXML_NOBLANKS(1)) Possible values:
|
ns | Optional. Specifies a namespace prefix or URI |
is_prefix | Optional. Specifies a Boolean value. TRUE if ns is a prefix. FALSE if ns is a URI. Default is FALSE |
Détails techniques
Valeur de retour : | Un objet SimpleXMLElement en cas de succès. FAUX en cas d'échec |
---|---|
Version PHP : | 5+ |
Plus d'exemples
Exemple
Sortez les données de chaque élément de la chaîne XML :
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Do not forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>
Exemple
Affichez le nom et les données de l'élément pour chaque nœud enfant dans la chaîne XML :
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Do not forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
echo $xml->getName() . "<br>";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br>";
}
?>
❮ Référence PHP SimpleXML