简体   繁体   中英

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?

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() 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 is enabled.

If allow_url_fopen is not enabled, you'll have to be ready to fallback to a solution based on curl .

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!

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM