Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用simpleXML输出BR标记_Php_Newline_Simplexml_Domdocument - Fatal编程技术网

Php 使用simpleXML输出BR标记

Php 使用simpleXML输出BR标记,php,newline,simplexml,domdocument,Php,Newline,Simplexml,Domdocument,我想把文本字符串“hello there”分成两行。 为此,我需要simpleXML在输出文件result.xml中创建“br标记”,但我只得到代码br <?php // DOMDocument $dom = new DomDocument('1.0', 'UTF-8'); $dom->formatOutput = true; $html = $dom->appendChild($dom->createElement("html")); $xmlns = $dom

我想把文本字符串“hello there”分成两行。 为此,我需要simpleXML在输出文件result.xml中创建“br标记”,但我只得到代码
br

<?php

// DOMDocument

$dom = new DomDocument('1.0', 'UTF-8');
$dom->formatOutput = true;

$html = $dom->appendChild($dom->createElement("html"));

$xmlns = $dom->createAttribute('xmlns');
$xmlns->value = 'http://www.w3.org/1999/xhtml';
$html->appendChild($xmlns);

// SimpleXML

$sxe = simplexml_import_dom($dom);
$head = $sxe->addChild('head', ' ');
$body = $sxe->addChild('body', 'hello <br> there');

echo $sxe->asXML('result.xml');

首先,PHP的SimpleXML扩展只适用于XML,而不适用于HTML。您在设置代码中正确地提到了XHTML,但这意味着您需要使用XML自动关闭元素,如

,而不是HTML未关闭标记,如

其次,
addChild
方法将文本内容作为其第二个参数,而不是原始文档内容;如您所见,它将自动为您转义

SimpleXML实际上是围绕着一种严格的元素树XML设计的,而不是像XHTML这样元素与文本内容交织在一起的标记语言,因此在这种情况下,最好还是坚持使用DOM

即使这样,恐怕也没有JS“innerhtml”属性的等价物,因此我相信您必须将文本和
br
元素添加为单独的节点,例如

$body = $html->appendChild( $dom->createElement('head') );

$body->appendChild( $dom->createTextNode('hello') );
$body->appendChild( $dom->createElement('br') );
$body->appendChild( $dom->createTextNode('world') );

我使用的是DOMDocument,但我希望通过使用SimpleXML来减少冗长的编码量,在SimpleXML还不够的情况下,我将使用DOMDocument进行授权。在试用了SimpleXML并意识到其限制后,我决定只使用DOMDocument。@是的,一般来说,我非常喜欢SimpleXML,但它在读方面比写方面更强,并且对HTML中常见的结构的支持也有限,因此,DOM可能是这项工作的合适工具。:)
$body = $html->appendChild( $dom->createElement('head') );

$body->appendChild( $dom->createTextNode('hello') );
$body->appendChild( $dom->createElement('br') );
$body->appendChild( $dom->createTextNode('world') );