viernes, 17 de junio de 2011

PHP: Leer un XML usando DOMDocument

Dejo a disposición un ejemplo sencillo de como leer un XML con la clase DOMDocument.

XML:

<catalog>
<catalog-name>My Favorite Music</catalog-name>
<cd id="cd-001">
<title value="Empire Burlesque" />
<artist value="Bob Dylan" />
<country value="USA" />
<company value="Columbia" />
<price value="10.90" />
<year value="1985" />
</cd>
<cd id="cd-002">
<title value="Hide your heart" />
<artist value="Bonnie Tyler" />
<country value="UK" />
<company value="CBS Records" />
<price value="9.90" />
<year value="1988" />
</cd>
<cd id="cd-003">
<title value="Greatest Hits" />
<artist value="Dolly Parton" />
<country value="USA" />
<company value="RCA" />
<price value="9.90" />
<year value="1982" />
</cd>
</catalog>

Código:

<?php
$cdCatalogXMLReader = new CDCatalogXMLReader();
$cdCatalogXMLReader->showCatalogAsTable('cd-catalog.xml');

class CDCatalogXMLReader {
public function showCatalogAsTable($xmlPath) {
// Loads XML.
$doc = new DOMDocument();
$doc->load($xmlPath);

// Reading tag's value.
$title = $doc->getElementsByTagName("catalog-name")
->item(0)->nodeValue;

echo "<h1>$title</h1>";

// Reading all elements with tag name="cd".
$cds = $doc->getElementsByTagName( "cd" );
echo '<table border="1">';
echo '<tr><th>ID</th><th>Title</th><th>Artist</th><th>Country</th><th>Company</th><th>Price</th><th>Year</th></tr>';

foreach ($cds as $cd) {
echo '<tr>';
// Reading attributes.
echo '<td>' . $cd->getAttribute('id') . '</td>';
echo '<td>' . $cd->getElementsByTagName("title")->item(0)->getAttribute('value') . '</td>';
echo '<td>' . $cd->getElementsByTagName("artist")->item(0)->getAttribute('value') . '</td>';
echo '<td>' . $cd->getElementsByTagName("country")->item(0)->getAttribute('value') . '</td>';
echo '<td>' . $cd->getElementsByTagName("company")->item(0)->getAttribute('value') . '</td>';
echo '<td>' . $cd->getElementsByTagName("price")->item(0)->getAttribute('value') . '</td>';
echo '<td>' . $cd->getElementsByTagName("year")->item(0)->getAttribute('value') . '</td>';
echo '</tr>';
}
echo '</table>';
}
}
?>

Salida:

My Favorite Music

IDTitleArtistCountryCompanyPriceYear
cd-001Empire BurlesqueBob DylanUSAColumbia10.901985
cd-002Hide your heartBonnie TylerUKCBS Records9.901988
cd-003Greatest HitsDolly PartonUSARCA9.901982

No hay comentarios:

Publicar un comentario