从Wikipedia API检索数组元素

时间:2018-03-31 18:08:57

标签: php arrays wikipedia-api

我和这个问题的作者有完全相同的问题:https://stackoverflow.com/a/17166962/766141但是那里的答案并不适合我。

API请求:

$searchQuery = str_replace(" ","+",$value);
$url = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=' . $searchQuery . '&format=json&explaintext&redirects&inprop=url';
$scrape = file_get_contents($url);

方法#1:

$data = json_decode($scrape, true);

$pageid = $data->query->pages[0];
echo $data->query->pages->$pageid->canonicalurl;

节目:

Notice: Trying to get property of non-object

方法#2:

$data = json_decode($scrape, true);

$pageid = $data['query']['pages'][0];
echo $data['query']['pages'][$pageid]['canonicalurl'];

节目:

Notice: Undefined offset: 0

当我将$pageid的值更改为3395时(这是我尝试检索数据的页面ID) - 一切都按预期工作,所以我只有检索页面ID的问题。

编辑: print_r($data)返回:

Array ( [batchcomplete] => [query] => Array ( [redirects] => Array ( [0] => Array ( [from] => Buddha [to] => Gautama Buddha ) ) [pages] => Array ( [3395] => Array ( [pageid] => 3395 [ns] => 0 [title] => Gautama Buddha [extract] => Gautama Buddha (c. 563/480 – c. 483/400 BCE), also known as Siddhārtha Gautama, Shakyamuni Buddha, or simply the Buddha, after the title of Buddha, was an ascetic (śramaṇa) and sage, on whose teachings Buddhism was founded. He is believed to have lived and taught mostly in the eastern part of ancient India sometime between the 6th and 4th centuries BCE. Gautama taught a Middle Way between sensual indulgence and the severe asceticism found in the śramaṇa movement common in his region. He later taught throughout other regions of eastern India such as Magadha and Kosala. Gautama is the primary figure in Buddhism. He is believed by Buddhists to be an enlightened teacher who attained full Buddhahood and shared his insights to help sentient beings end rebirth and suffering. Accounts of his life, discourses and monastic rules are believed by Buddhists to have been summarized after his death and memorized by his followers. Various collections of teachings attributed to him were passed down by oral tradition and first committed to writing about 400 years later. In Vaishnava Hinduism, the historic Buddha is considered to be an avatar of the Hindu god Vishnu. Of the ten major avatars of Vishnu, Vaishnavites believe Gautama Buddha to be the ninth and most recent incarnation. [contentmodel] => wikitext [pagelanguage] => en [pagelanguagehtmlcode] => en [pagelanguagedir] => ltr [touched] => 2018-03-31T10:45:06Z [lastrevid] => 833197460 [length] => 109689 [fullurl] => https://en.wikipedia.org/wiki/Gautama_Buddha [editurl] => https://en.wikipedia.org/w/index.php?title=Gautama_Buddha&action=edit [canonicalurl] => https://en.wikipedia.org/wiki/Gautama_Buddha ) ) ) )

1 个答案:

答案 0 :(得分:1)

您可以使用reset()来获取数组的第一个元素。

$data = json_decode($scrape, true);
$page = reset($data['query']['pages']);
echo $page['canonicalurl'];
相关问题