This is what I tried:
$doc = new DOMDocument();
$jsonurl = "http://v1.syndication.nhschoices.nhs.uk/.json?apikey=xxxxxx";
$doc->load($jsonurl);
var_dump(json_decode($doc));
var_dump(json_decode($doc, true));
The output is NULL NULL for the 2 var_dumps.
The JSON returned from the url looks like this (after view source):
[{"Text":"Live Well","Uri":"http:\/\/v1.syndication.nhschoices.nhs.uk\/livewell?apikey=xxxxx"},{"Text":"Conditions","Uri":"http:\/\/v1.syndication.nhschoices.nhs.uk\/conditions?apikey=xxxxx"},{"Text":"Organisations","Uri":"http:\/\/v1.syndication.nhschoices.nhs.uk\/organisations?apikey=xxxxx"},{"Text":"Carers Direct","Uri":"http:\/\/v1.syndication.nhschoices.nhs.uk\/carersdirect?apikey=xxxxx"}]
Is this valid?
-
1What does var_dump($doc) output. Is it valid json?Belinda– Belinda2011年03月11日 11:51:45 +00:00Commented Mar 11, 2011 at 11:51
-
2Why are you loading the JSON into a DOMDocument? JSON != XML.mdm– mdm2011年03月11日 11:52:29 +00:00Commented Mar 11, 2011 at 11:52
-
Just put the JSON through jsonlint.com and it came out as valid :/JohnnyBizzle– JohnnyBizzle2011年03月11日 13:25:32 +00:00Commented Mar 11, 2011 at 13:25
4 Answers 4
If that URL returns a JSON string, you should not use the DOMDocument class to load it : that class is to manipulate XML data.
Instead, you probably should do something like this, using [**`file_get_contents()`**][2] to do the HTTP request, and get its raw result :
$url = 'http://v1.syndication.nhschoices.nhs.uk/.json?apikey=xxxxxx';
$json_string = file_get_contents($url);
$data = json_decode($json_string);
var_dump($data);
As a sidenote : using `file_get_contents()` to make HTTP requests will only work if [`allow_url_fopen`][3] is enabled.
If allow_url_fopen is not enabled, you'll have to be ready to fallback to a solution based on curl.
3 Comments
You're trying to somehow decode a DOMDocument. json_decode works on strings. What is the relationship between a DOM document and a JSON string? Not very much at all. Pick one!
Comments
@Pascal MARTIN
With a slight modification it works:
$jsonurl = 'http://v1.syndication.nhschoices.nhs.uk/.json?apikey=XXXXXX';
$jsonstr = json_encode(file_get_contents($jsonurl));
$data = json_decode($jsonstr);
var_dump(json_decode($data));
I added json_encode around the file_get_contents call. Thanks all for the help :)
2 Comments
json_encode either takes an array or object as input, but not a string.http://v1.syndication.nhschoices.nhs.uk/.json
I think your url is not valid? /.json maybe should be /something.json or maybe /json
5 Comments
.htaccess. Windows has brainwashed you into thinking that every file must be "file.ext", which is simply not true.