将JSON结果获取到PHP数组中.怎么样?

Joh*_*zle 0 php json

这是我试过的:

$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));
Run Code Online (Sandbox Code Playgroud)

2 var_dumps的输出为NULL NULL.

从url返回的JSON看起来像这样(在查看源之后):

[{"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"}]
Run Code Online (Sandbox Code Playgroud)

这有效吗?

Pas*_*TIN 9

如果该URL返回JSON字符串,则不应使用DOMDocument类来加载它:该类用于处理XML数据.


相反,您可能应该做这样的事情,使用file_get_contents()HTTP请求,并获得其原始结果:

$url = 'http://v1.syndication.nhschoices.nhs.uk/.json?apikey=xxxxxx';
$json_string = file_get_contents($url);
$data = json_decode($json_string);
var_dump($data);
Run Code Online (Sandbox Code Playgroud)


作为旁注:file_get_contents()用于发出HTTP请求只有在allow_url_fopen启用时才有效.

如果allow_url_fopen未启用,则必须准备好回退到基于curl的解决方案.