14.13 XML-Dokumente aus PHP-Datenstrukturen erzeugen

Problem

Sie möchten aus einem Array oder PHP-Objekt ein XML-Dokument erzeugen.

Lösung

Verwenden Sie das PEAR-Paket XML_Serializer.

require_once 'XML/Serializer.php';

$shows = array(array('name'     => 'Simpsons',
                     'kanal'    => 'FOX',
                     'beginn'   => '20:00',
                     'dauer'    => '30'),

               array('name'     => 'Law & Order',
                     'kanal'    => 'NBC',
                     'beginn'   => '20:00',
                     'dauer'    => '60'));

$serializer = new XML_Serializer();
$serializer->setOption('indent', '    ');
$serializer->setOption('rootName', 'shows');
$serializer->setOption('defaultTagName', 'show');

$success = $serializer->serialize($shows);
if (PEAR::isError($success)) {
    die($success->getMessage());
}
print $serializer->getSerializedData();

Diskussion

Obwohl PHP 5 verschiedene ...

Get PHP 5 Kochbuch, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.