如何使用 SimpleXMLElement 获取 CDATA [重复]
Posted
技术标签:
【中文标题】如何使用 SimpleXMLElement 获取 CDATA [重复]【英文标题】:How to get CDATA using SimpleXMLElement [duplicate] 【发布时间】:2014-10-27 02:17:51 【问题描述】:我正在尝试解析以下 XML 结果
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE WEBCNPDATA [<!ELEMENT WEBCNPDATA (SUCCESS,COUNT,SEARCHID,REPORTID,DATA)><!ELEMENT SUCCESS (#PCDATA)><!ELEMENT COUNT (#PCDATA)><!ELEMENT SEARCHID (#PCDATA)><!ELEMENT REPORTID (#PCDATA)><!ELEMENT DATA (#PCDATA)><!ATTLIST DATA ENCODING CDATA #FIXED "base64"><!ATTLIST DATA COMPRESSION CDATA #FIXED "gzip">]><WEBCNPDATA><SUCCESS>true</SUCCESS><COUNT>9</COUNT><SEARCHID>11</SEARCHID><REPORTID>1</REPORTID><DATA ENCODING="base64" COMPRESSION="gzip"><![CDATA[H4sIAMsHBlQAA71YTW8cNwy951cYPmsGIiXq47gF0l5q1+gE2aPh2ttgiwYObDct9tf3kZpdb9KL
5EMNQyONl29F6vGR8sPdy93z7mX/4J73Lzt9/PXbH7t7fbFc3W5sOOi42GDT68enz8vu5TR9eQKI
+3j1Xg3a49Cey/pYl0fD10Uz3fzwIyxtPNhjaWNbHK1O82b08+YaRjYe7LG0sS2ORqd5M7r++CuM
bDzYY2ljWxyNTvNmtFW/tubVVn3amkfbV3+233rz4YN6o+PBHksb2+LkzXHejJYWvWWN3tKit6zR
]]></DATA></WEBCNPDATA>
我想要 CDATA
括号内的内容,但似乎不知道如何到达那里。当我将 XML 对象加载到 SimpleXMLElement
object(SimpleXMLElement)#1 (5)
["SUCCESS"]=>
string(4) "true"
["COUNT"]=>
string(1) "9"
["SEARCHID"]=>
string(2) "11"
["REPORTID"]=>
string(1) "1"
["DATA"]=>
object(SimpleXMLElement)#2 (1)
["@attributes"]=>
array(2)
["ENCODING"]=>
string(6) "base64"
["COMPRESSION"]=>
string(4) "gzip"
关于如何获取这些数据有什么建议吗?谢谢!
【问题讨论】:
【参考方案1】:您需要将DATA
元素显式转换为字符串:
$xml = <<<EOF
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE WEBCNPDATA [<!ELEMENT WEBCNPDATA (SUCCESS,COUNT,SEARCHID,REPORTID,DATA)><!ELEMENT SUCCESS (#PCDATA)><!ELEMENT COUNT (#PCDATA)><!ELEMENT SEARCHID (#PCDATA)><!ELEMENT REPORTID (#PCDATA)><!ELEMENT DATA (#PCDATA)><!ATTLIST DATA ENCODING CDATA #FIXED "base64"><!ATTLIST DATA COMPRESSION CDATA #FIXED "gzip">]><WEBCNPDATA><SUCCESS>true</SUCCESS><COUNT>9</COUNT><SEARCHID>11</SEARCHID><REPORTID>1</REPORTID><DATA ENCODING="base64" COMPRESSION="gzip"><![CDATA[H4sIAMsHBlQAA71YTW8cNwy951cYPmsGIiXq47gF0l5q1+gE2aPh2ttgiwYObDct9tf3kZpdb9KL
5EMNQyONl29F6vGR8sPdy93z7mX/4J73Lzt9/PXbH7t7fbFc3W5sOOi42GDT68enz8vu5TR9eQKI
+3j1Xg3a49Cey/pYl0fD10Uz3fzwIyxtPNhjaWNbHK1O82b08+YaRjYe7LG0sS2ORqd5M7r++CuM
bDzYY2ljWxyNTvNmtFW/tubVVn3amkfbV3+233rz4YN6o+PBHksb2+LkzXHejJYWvWWN3tKit6zR
]]></DATA></WEBCNPDATA>
EOF;
$document = simplexml_load_string($xml);
// Cast to string
$data = (string) $document->DATA;
var_dump($data);
输出:
string(308) "H4sIAMsHBlQAA71YTW8cNwy951cYPmsGIiXq47gF0l5q1+gE2aPh2ttgiwYObDct9tf3kZpdb9KL
5EMNQyONl29F6vGR8sPdy93z7mX/4J73Lzt9/PXbH7t7fbFc3W5sOOi42GDT68enz8vu5TR9eQKI
+3j1Xg3a49Cey/pYl0fD10Uz3fzwIyxtPNhjaWNbHK1O82b08+YaRjYe7LG0sS2ORqd5M7r++CuM
bDzYY2ljWxyNTvNmtFW/tubVVn3amkfbV3+233rz4YN6o+PBHksb2+LkzXHejJYWvWWN3tKit6zR
"
【讨论】:
以上是关于如何使用 SimpleXMLElement 获取 CDATA [重复]的主要内容,如果未能解决你的问题,请参考以下文章
如何打印 SimpleXMLElement 对象的特定数组元素
如何使用 SimpleXmlElement 编写 CDATA?
如何在不使用其父级的情况下设置 SimpleXmlElement 的文本值?