>  기사  >  백엔드 개발  >  php读取xml文档遇到实体符号时出错,该如何解决

php读取xml文档遇到实体符号时出错,该如何解决

WBOY
WBOY원래의
2016-06-13 13:44:10843검색

php读取xml文档遇到实体符号时出错
aa bb 
中间有这这格的实体符号时
会报出这种警告
( ! ) Warning: DOMDocument::load() [domdocument.load]: Entity 'nbsp' not defined in file:

读取xml文档是这样子
$xml = new DOMDocument("1.0","UTF-8");
$xml->load('myxml.xml');

------解决方案--------------------
能自己发现问题就好,既然不允许出现,你准备怎么解决呢?
------解决方案--------------------
FROM PHP Manual

PHP code

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 is a non-breaking space.</div>
XML;

$dd1 = new DOMDocument();
$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"?>


]>
<div>This is a non-breaking space.</div>
XML;

$dd2 = new DOMDocument();
$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., ), 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.
<br><font color="#e78608">------解决方案--------------------</font><br>恭喜lz。~~<br>thanks  ZT_king
<br><font color="#e78608">------解决方案--------------------</font><br>
 和 &  这三个不能出现 <div class="clear">
                 
              
              
        
            </div>
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.