记载一个phper的历程!http://phperwuhan.blog.phpchina.com

解决php的loadXML()不能识别空格实体的问题

上一篇 / 下一篇  2008-04-09 16:51:32 / 个人分类:php->xml

来源:http://phperwuhan.blog.163.com/blog/static/4114260220083945114254/

When using loadXML() to parse a string that contains entity references (e.g.,  ), be sure that those entity references are properly declared through the use of a DOCTYPE declaration; otherwise, loadXML() will not be able to interpret the string.

Example:
<?php
$str
= <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd1= newDOMDocument
();
$dd1->loadXML($str
);

echo
$dd1->saveXML
();
?>

Given the above code, PHP will issue a Warning about the entity 'nbsp' not being properly declared.  Also, the call to saveXML() will return nothing but a trimmed-down version of the original processing instruction...everything else is gone, and all because of the undeclared entity.

Instead, explicitly declare the entity first:
<?php
$str
= <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE root
[

<!ENTITY nbsp "&#160;">
]>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd2= newDOMDocument
();
$dd2->loadXML($str
);

echo
$dd2->saveXML
();
?>

Since the 'nbsp' entity is defined in the DOCTYPE, PHP no longer issues that Warning; the string is now well-formed, and loadXML() understands it perfectly.

You can also use references to external DTDs in the same way (e.g., <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"
http://www.w3.org/TR/html4/strict.dtd">), which is particularly important if you need to do this for many different documents with many different possible entities.

Also, as a sidenote...entity references created by createEntityReference() do not need this kind of explicit declaration.

 


TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

Open Toolbar