user1870041
user1870041

Reputation: 21

How to decode HTML entities when saving an XML file?

I have the following code in my PHP script:

$str = '<item></item>';
$xml = new DOMDocument('1.0', 'UTF-8');
$xml->formatOutput = true;
$xml->load('file.xml');
$items = $addon->getElementsByTagName('items')->item(0);
$items->nodeValue = $str;
$xml->save('file.xml');

In the saved file.xml I see the following:

&lt;item&gt;&lt;\item&gt;

How can I save it in the XML file without encoding HTML entities?

Upvotes: 2

Views: 1051

Answers (1)

Alf Eaton
Alf Eaton

Reputation: 5463

Use a DOMDocumentFragment:

<?php

$doc = new DOMDocument();
$doc->load('file.xml'); // '<doc><items/></doc>'

$item = $doc->createDocumentFragment();
$item->appendXML('<item id="1">item</item>');

$doc->getElementsByTagName('items')->item(0)->appendChild($item);
$doc->save('file.xml');

If you're appending to the root element, use $doc->documentElement->appendChild($item); instead of getElementsByTagName.

Upvotes: 1

Related Questions