首页 > 解决方案 > simplexml_load_string 不使用 php 转换特殊字符

问题描述

我正在尝试使用 CURL 请求将 xml 转换为 json,但特殊字符未正确解码。

下面是我的代码

function APIRequest($zip) {

   $URL = "http://www.example.com";

   $options = array(
       CURLOPT_RETURNTRANSFER => true,   // return web page
       CURLOPT_HEADER         => false,  // don't return headers
       CURLOPT_FOLLOWLOCATION => true,   // follow redirects
       CURLOPT_ENCODING       => "",     // handle compressed
       CURLOPT_USERAGENT      => "test", // name of client
       CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
   );

   $ch = curl_init($URL);

   curl_setopt_array($ch, $options);

   $response = curl_exec($ch);
   curl_close($ch);

   $xml = simplexml_load_string(utf8_encode($response));
   $json = json_encode($xml);
   $json_response = json_decode($result);
   return $json_response;
}

标签: phpcurlphp-curl

解决方案


试试下面的代码(你可以用file_get_contents()带有 cURL 的函数替换)。

<?php
header('Content-type: text/html; charset=utf-8');

// converts XML content to JSON
// receives the URL address of the XML file. Returns a string with the JSON object
function XMLtoJSON($xml) {
  $xml_cnt = file_get_contents($xml);    // gets XML content from file
  $xml_cnt = str_replace(array("\n", "\r", "\t"), '', $xml_cnt);    // removes newlines, returns and tabs

  // replace double quotes with single quotes, to ensure the simple XML function can parse the XML
  $xml_cnt = trim(str_replace('"', "'", $xml_cnt));
  $simpleXml = simplexml_load_string($xml_cnt);

  return json_encode($simpleXml);    // returns a string with JSON object
}

echo XMLtoJSON('test1.xml');

推荐阅读