Reputation: 27709
Can anybody suggest a good and stable class to encode and decode XML in PHP?
found this example on php.net, but can't make it work.. no error msgs is returned
$sxe = new SimpleXMLElement();
$sxe->addAttribute('type', 'documentary');
$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');
$characters = $movie->addChild('characters');
$character = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');
$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');
echo $sxe->asXML();
Upvotes: 3
Views: 9236
Reputation: 3128
By encode/decode do you mean write/read? XML is not code, just markup. There is something called character/entity encoding for XML, though.
PHP has basically two class or libraries to work with. SimpleXML and DOMElement. You'll have to check your phpinfo to see if they are enabled and php.ini to enable them.
Upvotes: -1
Reputation:
SimpleXML would probably be the easiest. Example:
<root>
<node>
<sub>Text</sub>
</node>
</root>
$xml = new SimpleXMLElement('xml_file.xml', 0, true);
echo $xml->node->sub; // Displays "Text"
Edit:
In response to your code that isn't working, you need to include a root node in the initiation of the class:
$sxe = new SimpleXMLElement('<root />');
Upvotes: 6