DOMDocument appendXML带有特殊字符 [英] DOMDocument appendXML with special characters

查看:147
本文介绍了DOMDocument appendXML带有特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从我的数据库中检索了一些html字符串,我想将这些字符串解析到我的DOMDocument中。

I am retreiving some html strings from my database and I would like to parse these strings into my DOMDocument. The problem is, that the DOMDocument gives warnings at special characters.


警告:
DOMDocumentFragment :: appendXML()
[domdocumentfragment.appendxml]:
实体:第2行:解析器错误:实体
'nbsp'没有在
中定义b page.php
在189行

Warning: DOMDocumentFragment::appendXML() [domdocumentfragment.appendxml]: Entity: line 2: parser error : Entity 'nbsp' not defined in page.php on line 189

我想知道为什么,我想知道如何解决这个问题。这是我的页面的一些代码片段。如何修复这些警告?

I wonder why and I wonder how to solve this. This are some code fragments of my page. How can I fix these kind of warnings?

$doc = new DOMDocument();

// .. create some elements first, like some divs and a h1 ..

while($row = mysql_fetch_array($result))
{
    $messageEl = $doc->createDocumentFragment();
    $messageEl->appendXML($row['message']); // gives it's warnings here!

    $otherElement->appendChild($messageEl);
}

echo $doc->saveHTML();

我还发现了一些有关验证的内容,但是当我应用该功能时,我的页面将不再加载。我试过的代码就是这样。

I also found something about validation, but when I apply that, my page won't load anymore. The code I tried for that was something like this.

$implementation = new DOMImplementation();
$dtd = $implementation->createDocumentType('html','-//W3C//DTD XHTML 1.0 Transitional//EN','http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd');

$doc = $implementation->createDocument('','',$dtd);
$doc->validateOnParse = true;
$doc->formatOutput = true;

// in the same whileloop, I used the following:
$messageEl = $doc->createDocumentFragment();
$doc->validate(); // which stopped my code, but error- and warningless.
$messageEl->appendXml($row['message']);

提前致谢!

Thanks in advance!

推荐答案

XML中没有& nbsp; 。定义了实际 name 的唯一字符实体(而不是使用数字引用)是& amp; & lt; & gt; & quot; & $ <$ code>。

There is no &nbsp; in XML. The only character entities that have an actual name defined (instead of using a numeric reference) are &amp;, &lt;, &gt;, &quot; and &apos;.

这意味着您必须使用非破坏空间的数值等价物, code>&#160; 或(十六进制)&#xA0;

That means you have to use the numeric equivalent of a non-breaking space, which is &#160; or (in hex) &#xA0;.

如果您尝试将HTML保存到XML容器中,请将其另存为文本。 HTML和XML可能看起来很相似,但它们非常独特。 appendXML()需要格式良好的XML作为参数。使用 nodeValue 属性代替它,它将对您的HTML字符串进行XML编码,而不会有任何警告。

If you are trying to save HTML into an XML container, then save it as text. HTML and XML may look similar but they are very distinct. appendXML() expects well-formed XML as an argument. Use the nodeValue property instead, it will XML-encode your HTML string without any warnings.

// document fragment is completely unnecessary
$otherElement->nodeValue = $row['message'];

这篇关于DOMDocument appendXML带有特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆