数组到XML:如何将HTML作为对象导入DOMDocument


Array to XML: Howto import HTML as object to DOMDocument?

可能重复:
如何将HTML插入PHP DOMNode
PHP和DOMDocument

我正在尝试编写一个类,该类使用DOMDocument将数组转换为XML,并在此基础上将HTML导入DOM文档。问题是HTML没有导入到DOM文档中,而是作为文本字符串导入(例如,HTML标记在生成的XML文档的源中显示为&lt;p&gt;,而不是<p>(。

更新:根据Hakre的要求直接添加到此问题中的代码。该代码有点被黑客入侵,但有效——不过,按照Hakre的建议,去掉DomDocument的扩展会很有趣。

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;

附言:请不要关闭这个问题,因为我不认为这是重复的。谢谢

在第二段代码的第15行尝试html_entity_decode($value),但为什么要将HTML作为HTML,因为这样它就会被解释为XML。

更新对不起,上面的那个不起作用,这个也不起作用:

$this
    ->createElement($element)
    ->createTextNode(is_array($value) ? null : $value ));

最后我自己试过了:

我认为这是最好的解决方案:http://codepad.org/PpyewkVd