2016-09-05 22 views
0

我想从外部API加载一些XML并将其变成一个simplexml字符串。我使用cURL跨域代理脚本来获取XML,但是当我通过simplexml_load_string函数运行XML时,我得到的只是一个白色屏幕。来自外部XML的simplexml_load_string返回白页

如果有办法将它变成JSON更容易,我会很高兴沿着这条路线走,因为XML不是我的特长。

这里是下面的代码+ XML我使用:

外部XML文件:

<Sensors xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Sensor> 
     <ID>12</ID> 
     <Name>EFM W.level</Name> 
     <Series>Level</Series> 
     <Unit>m</Unit> 
    </Sensor> 
    <Sensor> 
     <ID>13</ID> 
     <Name>EFM Wave h.</Name> 
     <Series>Height</Series> 
     <Unit>m</Unit> 
    </Sensor> 
</Sensors> 

PHP:

<?php 

    $url = 'LINK TO EXTERNAL XML'; 
    $headers = ($_POST['headers']) ? $_POST['headers'] : $_GET['headers']; 
    $mimeType = ($_POST['mimeType']) ? $_POST['mimeType'] : $_GET['mimeType']; 

    $session = curl_init($url); 

    if ($_POST['url']) { 
     $postvars = ''; 
     while ($element = current($_POST)) { 
      $postvars .= key($_POST).'='.$element.'&'; 
      next($_POST); 
     } 
     curl_setopt($session, CURLOPT_POST, true); 
     curl_setopt($session, CURLOPT_POSTFIELDS, $postvars); 
    } 

    curl_setopt($session, CURLOPT_HEADER, ($headers == "true") ? true : false); 
    curl_setopt($session, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true); 

    $response = curl_exec($session); 

    if ($mimeType != "") { 
     header("Content-Type: ".$mimeType); 
    } 

    $xml = simplexml_load_string($response); 

    print_r($xml); 

    curl_close($session); 

?> 

参考,跨域代理脚本我” m使用是 - https://github.com/abdul/php-proxy/blob/master/proxy.php

谢谢。

+0

确定你在'$ response'变量中有正确的内容吗? – Gedweb

+0

当我回声$回应我得到这个 - > https://s13.postimg.org/avuosdix3/Screen_Shot_2016_09_05_at_13_33_09.png –

回答

1

原来,这个XML是UTF-16编码的。显然simplexml不喜欢这个,所以我用下面的正则表达式将它改为UTF-8。

$xml = simplexml_load_string(preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $response)); 
+0

你的意思是XML声明一个破/错的编码,你解决了这个问题。在XML声明中替换编码值不会更改文档的编码。如果您修复了作品,那么您将UTF-8声明为UTF-16。 – ThW

+0

是的,但是我无法改变输出XML的编码。因此,为什么我必须按照我的方式去做。据我所知,迄今为止,没有任何东西被破坏,一切都在发挥作用。这会产生什么问题吗? –

+0

这只是表示外部API返回UTF-8,但声明它是UTF-16。它被打破。 DOM可以加载不同的编码,但声明必须与编码匹配。 – ThW