Ricerca…


Analisi dell'HTML da una stringa

PHP implementa un parser compatibile con DOM 2 , che consente di lavorare con HTML usando metodi familiari come getElementById() o 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;

Uscite:

Hello, World!

Nota che PHP emetterà avvisi su qualsiasi problema con l'HTML, specialmente se stai importando un frammento di documento. Per evitare questi avvertimenti, dire alla libreria DOM (libxml) di gestire i propri errori chiamando libxml_use_internal_errors() prima di importare il vostro HTML. È quindi possibile utilizzare libxml_get_errors() per gestire gli errori, se necessario.

Utilizzando 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;

Uscite:

Hello, World!

SimpleXML

Presentazione

  • SimpleXML è una libreria PHP che fornisce un modo semplice per lavorare con documenti XML (in particolare la lettura e l'iterazione attraverso dati XML).

  • L'unica limitazione è che il documento XML deve essere ben formato.

Analisi dell'XML mediante approccio procedurale

// 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

Analisi dell'XML usando l'approccio 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.

Accesso a bambini e attributi

  • Quando SimpleXML analizza un documento XML, converte tutti i suoi elementi o nodi XML in proprietà dell'oggetto risultante SimpleXMLElement
  • Inoltre, converte gli attributi XML in un array associativo a cui si può accedere dalla proprietà a cui appartengono.

Quando conosci i loro nomi:

$library = new SimpleXMLElement('library.xml', NULL, true);
foreach ($library->book as $book){
    echo $book['isbn'];
    echo $book->title;
    echo $book->author;
    echo $book->publisher;
}
  • Il principale svantaggio di questo approccio è che è necessario conoscere i nomi di ogni elemento e attributo nel documento XML.

Quando non conosci i loro nomi (o non vuoi conoscerli):

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
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow