simplexml_load_string从外部XML返回白页


simplexml_load_string from external XML returns white page

我试图从外部API加载一些XML并将其转换为simplexml字符串。我使用cURL跨域代理脚本来获取XML,但是当我通过simplexml_load_string函数运行XML时,我得到的只是一个白屏。

如果有一种更容易的方法把它转换成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);
?>

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

谢谢。

结果证明XML是UTF-16编码的。显然simplexml不喜欢这样,所以我使用以下正则表达式将其更改为UTF-8。

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