[英]Help with consuming JSON feed with PHP & json_decode
I've having an issue with consuming a particular feed for a client. 我在为客户使用特定的Feed时遇到问题。 They have given me a remote URL and the response is a JSON string like so:
他们给了我一个远程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"}
]}
For example purposes, I've shrank the feed to show the format, but in actuality there are hundreds of affiliates. 出于示例目的,我缩小了提要以显示格式,但是实际上有数百个会员。 Anyway, I want to use PHP json_decode because in the end, I need these affiliates in an associative array.
无论如何,我想使用PHP json_decode,因为最后,我需要关联数组中的这些关联。
I've got something like this, but I just end up getting the raw string, and json_decode doesn't actually parse it into an associative array. 我有类似的东西,但是我最终得到的是原始字符串,而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);
It seems like I need to maintain the "\\n" characters in the feed itself, but these get stripped out when using: 似乎我需要在feed本身中维护“ \\ n”字符,但是在使用时这些字符会被剥离:
file_get_contents
Anyway, I think you know what I'm after, I'm just not sure what I'm doing wrong. 无论如何,我想你知道我在追求什么,我只是不确定自己在做什么错。 I appreciate the help in advance.
我先感谢您的帮助。 I've tried using jquery with jsonp but it would be more ideal this way since I need to sort through the array afterward and it doesn't need to be asynchronous.
我已经尝试过将jQueryp与jsonp结合使用,但是这样做会更理想,因为我需要在以后对数组进行排序,并且不需要异步。
Acorn 橡子
It is possible that your feed contains unicode text. 您的Feed中可能包含unicode文本。 Try:
尝试:
$decode = json_decode(addslashes($json), true)
Update: 更新:
Solved the problem. 解决了问题。 There are instances of
\\'s
in the json data which json_decode
doesn't handle properly. json数据中
json_decode
\\'s
实例,而json_decode
无法正确处理。 To solve this you need to double escape the \\
. 要解决此问题,您需要加倍转义
\\
。 This is what I did. 这就是我所做的。
<?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);
You're data feed escapes single quotes (apostrophes) with a backslash (eg \\'). 您的数据Feed用反斜杠转义单引号(撇号)(例如\\')。 The JSON spec doesn't say this should be done, and thus PHP doesn't behave correctly.
JSON规范没有说应该这样做,因此PHP无法正常运行。
See: http://bugs.php.net/bug.php?id=42708 请参阅: http : //bugs.php.net/bug.php?id=42708
You can try replacing all \\' with ': 您可以尝试将所有\\'替换为':
$json = str_replace('\\\'', "'", $json);
before calling json_decode. 在调用json_decode之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.