php - 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;
}
解决方案
试试下面的代码(你可以用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');
推荐阅读
- amazon-web-services - 无法在 AWS 上部署 jboss
- javascript - how to send requests inside loop to backend and use await and make the loop executes sequentially
- php - 带有 php 的 HTML 表单不能使用单个提交按钮。
- ios - 单击 Tableview 单元格时使用哪种方法更新 Rest Api 数据
- jquery - 如何使用jquery遍历表中每一行的隐藏字段值
- r - 我在 typeof(x) 中遇到错误:对象“ParcelArea.m2”。未找到
- python - OpenCV 流式传输 ip 相机总是返回 False
- javascript - 发出请求时 LoopbackJS 和 PostgreSQL 之间的连接出错
- boost - 将自定义提升与 CMake 联系起来
- docker-compose - Docker 撰写错误:构建包含不受支持的选项:'shm_size'