我想创建一个嵌入编码xhtml的xml文件。我已经单独编码了xhtml文件。在创建xml元素的过程中,我想在xml元素test
中添加xhtml的编码内容。在我添加并回显最终输出到浏览器后,浏览器中显示错误。
此页面包含以下错误:第9行第144列出现错误:编码错误以下是第一个错误之前的页面呈现。
<?php
$dom =new DOMDocument('1.0','utf-8');
$content = (file_get_contents("test_xmlencoding.xhtml"));
$element = $dom->createElement('test', $content);
$dom->appendChild($element);
header('Content-type: text/xml;');
echo $dom->saveXML();
?>
XHTML文件
<?xml version="1.0" ?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="TX21_HTM 21.0.406.501" name="GENERATOR" />
<title></title>
</head>
<body style="font-family:'Arial';font-size:12pt;text-align:left;">
<p lang="en-US" style="margin-top:0pt;margin-bottom:0pt;"><span style="font-family:'Verdana';font-size:9pt;">ABC1.</span></p>
<p lang="en-US" style="margin-top:0pt;margin-bottom:0pt;"><span style="font-family:'Verdana';font-size:9pt;">(ABC2)</span></p>
<p lang="en-US" style="margin-top:0pt;margin-bottom:0pt;"><span style="font-family:'Verdana';font-size:9pt;"> </span></p>
<p lang="en-US" style="margin-top:0pt;margin-bottom:0pt;"><span style="font-family:'Verdana';font-size:9pt;">ABC3</span></p>
</body>
</html>
当添加没有编码的xhtml内容时,输出在浏览器上呈现时没有错误。
我已尝试更换
$content = (file_get_contents("test_xmlencoding.xhtml"));
至
$content = htmlentities(file_get_contents("test_xmlencoding.xhtml"));
输出仅显示测试元素</test>
的结束标记。
DOMDocument::createElement()
的第二个参数和DOMNode::$nodeValue
属性只有部分转义。他们期望特殊字符已经作为实体转义——除了<
和>
。
$document = new DOMDocument();
$document->appendChild(
$tests = $document->createElement('tests')
);
$tests
->appendChild($document->createElement('test', 'a < b'));
$tests
->appendChild($document->createElement('test', 'a & b'));
echo $document->saveXML();
输出:
Warning: DOMDocument::createElement(): unterminated entity reference b in ... on line 9
<?xml version="1.0"?>
<tests><test>a < b</test><test/></tests>
方法参数不是DOM标准的一部分,并且属性的行为与规范不同。
在原始DOM中,您需要将内容添加为单独的文本节点。这也允许混合的子节点。现代DOM引入了DOMNode::$textContent
属性作为快捷方式。
这里有一个例子:
$xhtml = <<<'XHTML'
<?xml version="1.0" ?>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<em>a & b</em>
</body>
</html>
XHTML;
$document = new DOMDocument();
$document->appendChild(
$tests = $document->createElement('tests')
);
// append child element and set its text content
$tests
->appendChild($document->createElement('test'))
->textContent = $xhtml;
// append child element, then append child text node
$tests
->appendChild($document->createElement('test'))
->appendChild($document->createTextNode($xhtml));
$document->formatOutput = true;
echo $document->saveXML();
输出:注意双重转义的&amp;
。
<?xml version="1.0"?>
<tests>
<test><?xml version="1.0" ?>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<em>a &amp; b</em>
</body>
</html></test>
<test><?xml version="1.0" ?>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<em>a &amp; b</em>
</body>
</html></test>
</tests>