JohnnyBizzle
JohnnyBizzle

Reputation: 979

Get a JSON result into a PHP array. How?

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?

Upvotes: 0

Views: 1193

Answers (4)

JohnnyBizzle
JohnnyBizzle

Reputation: 979

@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 :)

Upvotes: 0

Ivan Ivanic
Ivan Ivanic

Reputation: 3054

http://v1.syndication.nhschoices.nhs.uk/.json

I think your url is not valid? /.json maybe should be /something.json or maybe /json

Upvotes: -1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385174

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!

Upvotes: 0

Pascal MARTIN
Pascal MARTIN

Reputation: 401012

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.

Upvotes: 9

Related Questions