Recherche…


Analyse HTML à partir d'une chaîne

PHP implémente un analyseur compatible DOM niveau 2 , vous permettant de travailler avec HTML en utilisant des méthodes familières comme getElementById() ou appendChild() .

$html = '<html><body><span id="text">Hello, World!</span></body></html>';

$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);

echo $doc->getElementById("text")->textContent;

Les sorties:

Hello, World!

Notez que PHP émettra des avertissements concernant tout problème avec le HTML, surtout si vous importez un fragment de document. Pour éviter ces avertissements, demandez à la bibliothèque DOM (libxml) de gérer ses propres erreurs en appelant libxml_use_internal_errors() avant d'importer votre code HTML. Vous pouvez ensuite utiliser libxml_get_errors() pour gérer les erreurs si nécessaire.

Utiliser XPath

$html = '<html><body><span class="text">Hello, World!</span></body></html>';

$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DOMXPath($doc);
$span = $xpath->query("//span[@class='text']")->item(0);

echo $span->textContent;

Les sorties:

Hello, World!

SimpleXML

Présentation

  • SimpleXML est une bibliothèque PHP qui permet de travailler facilement avec des documents XML (en particulier la lecture et l'itération de données XML).

  • La seule contrainte est que le document XML doit être bien formé.

Analyse XML en utilisant une approche procédurale

// Load an XML string
$xmlstr = file_get_contents('library.xml');
$library = simplexml_load_string($xmlstr);

// Load an XML file
$library = simplexml_load_file('library.xml');

// You can load a local file path or a valid URL (if allow_url_fopen is set to "On" in php.ini

Analyse XML en utilisant l'approche OOP

// $isPathToFile: it informs the constructor that the 1st argument represents the path to a file,
// rather than a string that contains 1the XML data itself.

// Load an XML string
$xmlstr = file_get_contents('library.xml');
$library = new SimpleXMLElement($xmlstr);

// Load an XML file
$library = new SimpleXMLElement('library.xml', NULL, true);

// $isPathToFile: it informs the constructor that the first argument represents the path to a file, rather than a string that contains 1the XML data itself.

Accéder aux enfants et aux attributs

  • Lorsque SimpleXML analyse un document XML, il convertit tous ses éléments XML, ou ses nœuds, en propriétés de l'objet SimpleXMLElement résultant.
  • En outre, il convertit les attributs XML en un tableau associatif accessible à partir de la propriété à laquelle ils appartiennent.

Lorsque vous connaissez leurs noms:

$library = new SimpleXMLElement('library.xml', NULL, true);
foreach ($library->book as $book){
    echo $book['isbn'];
    echo $book->title;
    echo $book->author;
    echo $book->publisher;
}
  • L'inconvénient majeur de cette approche est qu'il est nécessaire de connaître les noms de chaque élément et attribut dans le document XML.

Lorsque vous ne connaissez pas leurs noms (ou que vous ne voulez pas les connaître):

foreach ($library->children() as $child){
    echo $child->getName();
    // Get attributes of this element
    foreach ($child->attributes() as $attr){
        echo ' ' . $attr->getName() . ': ' . $attr;
    }
    // Get children
    foreach ($child->children() as $subchild){
        echo ' ' . $subchild->getName() . ': ' . $subchild;
    }
}


Modified text is an extract of the original Stack Overflow Documentation
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow