解码XML以便使用simplexml_load_string()进行处理

时间:2014-02-26 16:36:11

标签: php xml simplexml

我有以下XML字符串:

$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>
\n<RESPONSE>\n
<STATUS>OK</STATUS>\n
<ClientID>0</ClientID>\n
<URLREDIRECT>https://www.mywebsite.co.uk/redirect/?tid=1020ca5888bc56018096d1f6eba98d&data=WwB7ACIAQwBsAGkAZQBuAHQASQBEACIAOgAiAHIAYQB0AGQAZQBjADAAMAAxADAAMAAyADAAMgAwADkAOQA5ADMAOQAzADgAOAA4ADIAOAAyADcAMwA3ADMAOAA0ADgANAA3ADgAMQAxADEAOAAyADgAIgAsACIAUwB1AGIASQBEACIAOgAiACIALAAiAEYAaQByAHMAdABOAGEAbQBlACIAOgAiAFMAaQBkAG4AZQB5AGUAcgBwACIALAAiAFMAdQByAE4AYQBtAGUAIgA6ACIAUwBtAGkAdABoAGUAcgB0AHQAdABwACIALAAiAE0AbwBiAGkAbABlACIAOgAiADAANwAwADAAMAAwADAANgA3ADYAOQAiACwAIgBFAG0AYQBpAGwAIgA6ACIAcwBpAGQAbgBlAHkALgBzAG0AaQB0AGgANgA3ADYAOQBAAHIAZwByAG8AdQBwAC4AYwBvAC4AdQBrACIALAAiAFAAbwBzAHQAQwBvAGQAZQAiADoAIgBTAEUANgAgADgAUgBUACIALAAiAEgAbwB1AHMAZQBOAHUAbQBiAGUAcgAiADoAIgBSAGkAYwBoAG0AbwBuAGQAIABIAG8AdQBzAGUAIgAsACIATgB1AG0ARABlAGIAdABzACIAOgAiADIAIgAsACIARABlAGIAdABsAGUAdgBlAGwAIgA6ACIAMgAwADAAMAAiACwAIgBBAGYAZgBvAHIAZABhAGIAaQBsAGkAdAB5ACIAOgAiADgAMAAiAH0AXQA=
</URLREDIRECT>\n
</RESPONSE>';

我正在尝试解码字符串,如下所示:

$decodedXML = html_entity_decode($xml, ENT_XML1);

然后解释为对象:

$xml = simplexml_load_string($decodedXML);

但是,在运行simplexml_load_string()函数时,我收到以下错误:

html_entity_decode() expects parameter 2 to be long, string given in
...

我不确定这是否是由于我解码XML字符串的方式?有什么建议吗?

2 个答案:

答案 0 :(得分:1)

错误消息由ENT_XML1常量触发。如果您的PHP版本不知道,PHP将使用常量名称作为字符串。该函数不支持将字符串作为第二个参数。

为避免此类错误,请始终使用错误级别E_ALL进行开发,并显示通知。 PHP将发出通知,指出常量未知并用作字符串。

但解码XML字符串的XML实体可能会破坏它。小心。

答案 1 :(得分:0)

删除\ n字符并使用CDATA保持URL不被解析:

<?xml version="1.0" encoding="ISO-8859-1"?>
<RESPONSE>
<STATUS>OK</STATUS>
<ClientID>0</ClientID>
<URLREDIRECT><![CDATA[https://www.mywebsite.co.uk/redirect/?tid=1020ca5888bc56018096d1f6eba98d&data=WwB7ACIAQwBsAGkAZQBuAHQASQBEACIAOgAiAHIAYQB0AGQAZQBjADAAMAAxADAAMAAyADAAMgAwADkAOQA5ADMAOQAzADgAOAA4ADIAOAAyADcAMwA3ADMAOAA0ADgANAA3ADgAMQAxADEAOAAyADgAIgAsACIAUwB1AGIASQBEACIAOgAiACIALAAiAEYAaQByAHMAdABOAGEAbQBlACIAOgAiAFMAaQBkAG4AZQB5AGUAcgBwACIALAAiAFMAdQByAE4AYQBtAGUAIgA6ACIAUwBtAGkAdABoAGUAcgB0AHQAdABwACIALAAiAE0AbwBiAGkAbABlACIAOgAiADAANwAwADAAMAAwADAANgA3ADYAOQAiACwAIgBFAG0AYQBpAGwAIgA6ACIAcwBpAGQAbgBlAHkALgBzAG0AaQB0AGgANgA3ADYAOQBAAHIAZwByAG8AdQBwAC4AYwBvAC4AdQBrACIALAAiAFAAbwBzAHQAQwBvAGQAZQAiADoAIgBTAEUANgAgADgAUgBUACIALAAiAEgAbwB1AHMAZQBOAHUAbQBiAGUAcgAiADoAIgBSAGkAYwBoAG0AbwBuAGQAIABIAG8AdQBzAGUAIgAsACIATgB1AG0ARABlAGIAdABzACIAOgAiADIAIgAsACIARABlAGIAdABsAGUAdgBlAGwAIgA6ACIAMgAwADAAMAAiACwAIgBBAGYAZgBvAHIAZABhAGIAaQBsAGkAdAB5ACIAOgAiADgAMAAiAH0AXQA=]]></URLREDIRECT>
</RESPONSE>