2012-05-11 37 views
0

使用Wikiepdia API鏈接獲取有關某些世界已知字符的一些基本信息。如何使用php解析提要

例子:(About Dave Longaberger)

這將顯示如下

About Dave Longaberger

現在我的問題 我想解析XML得到<extract></extract>之間的這種基本的信息表現出來。

這是我的想法,但失敗了(I/O警告:未能加載外部實體)

<?PHP 
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Dave Longaberger&format=xml&exintro=1'; 

$xml = simplexml_load_file($url); 

// get extract 
$text=$xml->pages[0]->extract; 
// show title 
echo $text; 
?> 

另一個想法,但也失敗(未能打開流:HTTP請求失敗)

<?PHP 
function get_url_contents($url){ 
$crl = curl_init(); 
$timeout = 5; 
curl_setopt ($crl, CURLOPT_URL,$url); 
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout); 
$ret = curl_exec($crl); 
curl_close($crl); 
return $ret; 
} 

$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Dave Longaberger&format=xml&exintro=1"; 

$text = file_get_contents($url); 
echo $text; 
?> 

所以任何想法如何做到這一點。 〜感謝

更新(加入後用urlencode或rawurlencode仍無法正常工作)

$name = "Dave Longaberger"; 
$name = urlencode($name); 
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles='.$name.'&format=xml&exintro=1'; 
$text = file_get_contents($url); 

也沒有工作

$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Dave Longaberger&format=xml&exintro=1'; 
$url = urlencode($url); 
$text = file_get_contents($url); 

也不

$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles='.rawurlencode('Dave Longaberger').'&format=xml&exintro=1'; 
$text = file_get_contents($url); 

嘛,所以我真不」不知何故,看起來似乎是不可能的。

+1

腳本應使用一個信息用戶代理字符串與聯繫人信息,或者它們可以是封端的IP不另行通知。 – ccKep

回答

1

在捲曲請求中設置用戶代理標題,否則維基百科答覆錯誤403,否則禁止。

<?PHP 
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Dave+Longaberger&format=xml&exintro=1"; 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"); 
$xml = curl_exec($ch); 
curl_close($ch); 

echo $xml; 
?> 

或者:

ini_set("user_agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"); 
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Dave+Longaberger&format=xml&exintro=1"; 
$xml = simplexml_load_file($url); 

$extracts = $xml->xpath("/api/query/pages/page/extract"); 

var_dump($extracts); 
+0

完美:)非常感謝它的工作,yea看起來像它需要用戶代理標題添加在捲曲請求。 〜非常感謝 –

+0

用simplexml_load_file例子編輯了OP。 – ccKep