简体   繁体   English

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

[英]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. 2个var_dumps的输出为NULL NULL。

The JSON returned from the url looks like this (after view source): 从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"}]

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 . 如果该URL返回JSON字符串,则不应使用DOMDocument类加载它: 该类将处理XML数据


Instead, you probably should do something like this, using file_get_contents() to do the HTTP request, and get its raw result : 相反,您可能应该执行以下操作,使用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);


As a sidenote : using file_get_contents() to make HTTP requests will only work if allow_url_fopen is enabled. 附带说明:仅在启用allow_url_fopen情况下,使用file_get_contents()发出HTTP请求才有效。

If allow_url_fopen is not enabled, you'll have to be ready to fallback to a solution based on curl . 如果未启用allow_url_fopen则必须准备好使用基于curl的解决方案。

You're trying to somehow decode a DOMDocument . 您正在尝试以某种方式解码DOMDocument json_decode works on strings. json_decode适用于字符串。 What is the relationship between a DOM document and a JSON string? DOM文档和JSON字符串之间是什么关系? 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. 我在file_get_contents调用周围添加了json_encode。 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 /.json可能应该是/something.json/json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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