我像这样访问维基百科api: http://en.wikipedia.org/w/api.php?action=query∝extracts&format=xml&exsentences=2&exlimit=10&exintro=&explaintext=&redirects=&generator=search&gsrsearch=France&gsrlimit=10
这给了我xml,我有困难访问。我尝试了以下方法,但没有得到任何回报:
ini_set("user_agent", 'myemail');
$xml=simplexml_load_file('http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=xml&exsentences=2&exlimit=10&exintro=&explaintext=&redirects=&generator=search&gsrsearch=France&gsrlimit=10');
header('Content-Type: text/xml');
echo $xml->api->query->pages->page[0]->extract;
谁能告诉我我做错了什么?
try
$xml=simplexml_load_file('http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=xml&exsentences=2&exlimit=10&exintro=&explaintext=&redirects=&generator=search&gsrsearch=France&gsrlimit=10');
echo $xml->query->pages->page[0]->extract;
输出:-在第二次世界大战中,法国战役,也被称为法国的陷落,是指德国在1940年5月10日成功入侵法国和低地国家,击败了主要的法国军队。战役包括两个主要作战。
我会使用json api代替:将url字符串中的format=xml
更改为format=json
,然后执行:
$json = file_get_contents('http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exsentences=2&exlimit=10&exintro=&explaintext=&redirects=&generator=search&gsrsearch=France&gsrlimit=10');
$data = json_decode($json, true);
foreach ($data['query']['pages'] as $page) {
echo '<p>' . $page['extract'] . '</p>';
}
与json_decode你得到一个原生PHP数组,我发现比simplexml更直观,但这只是偏好。