Echo JSON PHP数组WIKI API

时间:2016-01-08 15:09:54

标签: php json

我不知道导出API的人

所以网址是:

https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&pithumbsize=200&titles=Jean-Claude%20Van%20Damme

我得到了

 {"batchcomplete":"","query":{"pages":{"89265":  {"pageid":89265,"ns":0,"title":"Jean-Claude Van Damme","thumbnail":{"source":"https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Jean-Claude_Van_Damme_2012.jpg/141px-Jean-Claude_Van_Damme_2012.jpg","width":141,"height":200},"pageimage":"Jean-Claude_Van_Damme_2012.jpg"}}}}

我只能导出来源?

现在我有了这段代码:

$json=file_get_contents("https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&pithumbsize=200&titles=$title");

$details=json_decode($json);

echo $details['thumbnail']['source'];

那我是谁?

2 个答案:

答案 0 :(得分:0)

您可以使用json_decode并传递true作为第二个参数。

来自文档:

  

当为TRUE时,返回的对象将被转换为关联数组。

然后我认为你在寻找的是:

$json=file_get_contents("https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&pithumbsize=200&titles=Jean-Claude%20Van%20Damme");
$details=json_decode($json, true);
$source = $details['query']['pages']['89265']['thumbnail']['source'];

echo $source;

将导致:

  

https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Jean-Claude_Van_Damme_2012.jpg/141px-Jean-Claude_Van_Damme_2012.jpg

答案 1 :(得分:0)

试试这个。

$json = file_get_contents("https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&pithumbsize=200&titles=Jean-Claude%20Van%20Damme");

$details = json_decode($json);

$pages = $details->query->pages;    

$output = '';
foreach ($pages as $pageid => $content){ 
    $image_url = $content->thumbnail->source;
    $title = $content->title;
    $output .= '<img src="'.$image_url.'"/>'.$title;
}

echo $output;