我正在尝试一个简单的PHP XML示例。
// code of PHP
===================================================
<?php
$string = <<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
XML;
print "BEGIN</br>";
print "String:</br>{$string}";
$xml = simplexml_load_string($string);
print "</br>XML Obj:</br>";
print_r($xml);
print "</br>Var Dump:</br>";
var_dump($xml);
print "</br>END";
?>
===================================================
输出似乎没问题
// output
===================================================
BEGIN
String:
George John Reminder Don't forget the meeting!
XML Obj:
SimpleXMLElement Object ( [to] => George [from] => John [heading] => Reminder [body] => Don't forget the meeting! )
Var Dump:
object(SimpleXMLElement)#1 (4) { ["to"]=> string(6) "George" ["from"]=> string(4) "John" ["heading"]=> string(8) "Reminder" ["body"]=> string(25) "Don't forget the meeting!" }
END
===================================================
当我尝试通过在其前面添加一些空格来格式化第一行heredoc样式字符串时,在跟随行<?xml version="1.0" encoding="ISO-8859-1"?>
之前添加两个空格,然后它总是无法输出$ xml对象信息。
// code of PHP
===================================================
<?php
$string = <<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
XML;
... ...
===================================================
// output
===================================================
BEGIN
String:
George John Reminder Don't forget the meeting!
XML Obj:
Var Dump:
bool(false)
END
希望有人可以帮助我!!! 非常感谢。
答案 0 :(得分:1)
这不是有效的XML。看看XML specs for documents:
document ::= prolog element Misc*
prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
document
从prolog
开始,描述了构建其他语法标记XML文档的内容。此可能包含XMLDecl
,它再次以<?xml
开头。简而言之:如果有声明,则在声明之前不允许有空格。
如果你在XML(你似乎是)的控制之下:只是不要这样做,我认为这是恶意的,因为每个人都不得不处理代码后你会想知道发生了什么。
如果您无法更改输入,因为其他人正在发送损坏的XML文件:
trim($string)
非XML。