使用php解析混合XML和HTML

时间:2017-09-28 00:55:39

标签: php json xml

我正在做一个卷曲请求并得到以下回复:

//....curl stuff....//
$result = curl_exec($curl);
curl_close ($curl);
print_R($result);


     <html><body onload="if (parent.submitterLoaded) 
parent.submitterLoaded();">{"AuthenticationType":0, 
"DateDisplayFormat":1, "SystemURL":"https://rmm.server.com", 
"Username”:”user”, "UserID":"12205_1", "Error":"", "Success":true, 
"ClientID":1, "SessionGuid":"9eb91231b04-feca-4704-b445-
cc5b369581e3", "tag":"", "LastRequestDateTime":"636421428277379996"}
 </body></html><?xml version="1.0" encoding="utf-8"?><soap:Envelope 
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body>
<LoginResponse xmlns="http://Iris.net" /></soap:Body></soap:Envelope>

我尝试过xml_parser_create和

$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

我得到一个乱七八糟的混乱。

Warning:  simplexml_load_string(): Entity: line 1: parser error : XML 
declaration allowed only at the start of the document in 
/var/www/cron/billing/test.php on line 68
PHP Warning:  simplexml_load_string(): b6-bd4dd8a0760b", 
"LastRequestDateTime":"636421426011959977"}</body></html><?xml in 
/var/www/cron/billing/test.php on line 68
PHP Warning:  simplexml_load_string():                                                                                
^ in /var/www/cron/billing/test.php on line 68

我可以在响应的{“Keys”区域看到一些似乎是json的内容。我怎样才能正确解析这个?

您需要提供哪些其他信息才能回答问题?

2 个答案:

答案 0 :(得分:1)

第一个警告表示解析器不喜欢第二部分<?xml version..。所以摆脱它:

$result = substr($result, 0, strpos($result, '<?xml version'));

然后拔出JSON字符串,使用:

$jsonString = (string) simplexml_load_string($result)->body;
$array = json_decode($jsonString);

答案 1 :(得分:0)

使用DOMDocument提取json,并使用json_decode

解析它
$domd=@DOMDocument::loadHTML($response);
$json_data=json_decode(trim($domd->getElementsByTagName("body")->item(0)->textContent));

现在可以像$UserID=$json_data->UserID;那样访问json中的内容,并且可以在$ domd中访问HTML中的内容,例如$loginResponse=$domd->getElementsByTagName("LoginResponse")->item(0)->textContent; - 没有看到任何有用的内容除了json之外的HTML,但是..