Possible Duplicate:
How to insert HTML to PHP DOMNode?
PHP and DOMDocument
I am trying to write a Class that converts an array to XML using DOMDocument - and on top of that imports HTML into the DOM document. Problem is that the HTML is not imported into the DOM document - it gets imported as a text string (for instance, HTML tags are shown as <p> instead of <p> in the source for the resulting XML document).
Update: Code added directly to this Question as requested by Hakre. The code is a bit hacked but works - it would be interesting though to get rid of the extend from DomDocument as suggested by Hakre.
class xmlizer extends DomDocument {
function __construct() {
parent::__construct();
}
function node_create($arr, $items = null) {
if (is_null($items))
$items = $this->appendChild($this->createElement("items"));
// Loop the array values.
foreach($arr as $element => $value) {
// If Array has numeric keys, use "node - else use $element.
$element = is_numeric( $element ) ? "node" : $element;
// Create element, add $value unless $value is an array - and append to main object ($items).
$fragment = $this->createElement($element, (is_array($value) ? null : $value));
$items->appendChild($fragment);
// Iterate if $value is an array, .
if (is_array($value)) {
self::node_create($value, $fragment);
}
}
}
public function __toString() {
// html_entity_decode() added by Micha. Thanks.
return html_entity_decode($this->saveXML());
}
}
// Build test Array with HTML string (for testing purposes only).
for($i=0;$i<3;$i++) {
$j = $i+1;
$array['example'][] = array(
"id" => $j,
"title" => "Title $j",
"description" => "<p>Text <strong>string</strong> nr. $j with <em>some</em> <code>HTML code</code>.</p>",
);
}
// Test: Run the code.
header("Content-Type:text/xml");
$xml = new xmlizer();
$xml->node_create($array);
echo $xml;
PS: Please don't close the Question as I don't think this is a duplicate. Thanks.
LIBXML_NOCDATA(compare read cdata from a rss feed). Not that this solves all your problems, but you can do the same with DOMDocument, see as well Gordon's links. In total all are referring to DOMDocument if you look closely.