从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 ) ) ) )

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

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

最新更新