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

php中文网
发布: 2016-06-13 13:44:10
原创
1128人浏览过

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-&gt;loadXML($str);

echo $dd1-&gt;saveXML();
?&gt;

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"?>
]&gt;
<div>This is a non-breaking space.</div>
XML;

$dd2 = new DOMDocument();
$dd2-&gt;loadXML($str);

echo $dd2-&gt;saveXML();
?&gt;

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> 和 &amp;  这三个不能出现 <div class="clear"></div>
登录后复制
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号