Reputation: 867
I've having an issue with consuming a particular feed for a client. They have given me a remote URL and the response is a JSON string like so:
{"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.
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.
$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:
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.
Acorn
Upvotes: 1
Views: 5405
Reputation: 692
You're data feed escapes single quotes (apostrophes) with a backslash (e.g. \'). The JSON spec doesn't say this should be done, and thus PHP doesn't behave correctly.
See: http://bugs.php.net/bug.php?id=42708
You can try replacing all \' with ':
$json = str_replace('\\\'', "'", $json);
before calling json_decode.
Upvotes: 4
Reputation: 5917
It is possible that your feed contains unicode text. 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. 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);
Upvotes: 5