我在为客户使用特定提要时遇到问题。他们给了我一个远程 URL,响应是一个 JSON 字符串,如下所示:
{"affiliate": [
{"ID":"1", "COUNTRY":"EXAMPLE", "NETWORK":"EXAMPLE", "PRIMARY":"EXAMPLE"},
{"ID":"2", "EXAMPLE":"EXAMPLE", "COUNTRY":"EXAMPLE", "NETWORK":"EXAMPLE", "PRIMARY":"EXAMPLE"},
{"ID":"3", "TITLE":"EXAMPLE", "COUNTRY":"EXAMPLE", "NETWORK":"EXAMPLE", "PRIMARY":"EXAMPLE"}
]}
出于示例目的,我缩小了提要以显示格式,但实际上有数百个附属机构。无论如何,我想使用 PHP json_decode,因为最终我需要将这些附属机构放在关联数组中。
我有类似的东西,但我最终只是得到原始字符串,而 json_decode 实际上并没有将其解析为关联数组。
$request_url = "http://exampleurl.com/feed"; //returns feed like above
$json = file_get_contents($request_url, true); //getting the file content
$decode = json_decode($json, true);
print_r($decode);
似乎我需要在提要本身中保留“\n”字符,但在使用时这些字符会被删除:
file_get_contents
无论如何,我想你知道我在追求什么,我只是不确定我做错了什么。我很感谢您提前提供的帮助。我尝试过将 jquery 与 jsonp 一起使用,但这种方式会更理想,因为我需要随后对数组进行排序,并且不需要异步。
橡子
最佳答案
您的 Feed 可能包含 unicode 文本。尝试:
$decode = json_decode(addslashes($json), true)
<小时/>
更新:
解决了问题。 json 数据中存在 \'s
实例,json_decode
无法正确处理。要解决这个问题,您需要对 \
进行双重转义。这就是我所做的。
<?php
error_reporting(E_ALL);
$request_url = 'http://midas.glam.com/publisher_directory_data?network=glam&country=US&publish=Y';
$json = file_get_contents($request_url);
$json = str_replace('\\', '\\\\', $json);
$decode = json_decode($json, true);
var_dump($decode);
关于php - 帮助使用 PHP 和 json_decode 使用 JSON feed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1200603/