2009-12-13 43 views
3

我注意到有一個問題有點類似於我的問題,只能用c#:link text。 讓我解釋一下:我對整個Web服務實現都很陌生,所以我在理解時遇到了一些困難(特別是由於MediaWiki API手冊模糊)。PHP連接到MediaWiki API並檢索數據

我要檢索的整個頁面作爲一個字符串在PHP(XML文件),然後在PHP處理它(我敢肯定還有其他更復雜的方式來解析XML文件,但不管): Main Page wikipedia 。我試過$fp = fopen($url,'r');。它輸出:HTTP request failed! HTTP/1.0 400 Bad Request。 API不需要密鑰來連接它。

你能詳細描述如何連接到API並獲取頁面作爲字符串?

編輯: 該網址是$url='http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Main Page';。我只是想將整個文件的內容讀入一個字符串中來使用它。

+0

你能告訴我們多一點代碼嗎? – Galen 2009-12-13 20:05:38

回答

7

連接到該API是檢索文件一樣簡單,

fopen

$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Main%20Page'; 
$fp = fopen($url, 'r'); 
while (!feof($fp)) { 
    $c .= fread($fp, 8192); 
} 
echo $c; 

file_get_contents

$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Main%20Page'; 
$c = file_get_contents($url); 
echo $c; 

如果你的服務器有fopen包裝以上兩個只能用啓用。

否則,如果您的服務器已安裝cURL你可以使用,

$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Main%20Page'; 
$ch = curl_init($url); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
$c = curl_exec($ch); 
echo $c; 
+0

非常感謝你!你知道我可以在我的本地apache上啓用fopen包裝嗎? – Gal 2009-12-13 20:20:27

+0

請確保您的php ini中的allow_url_fopen = 1。 http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen – Galen 2009-12-13 20:30:58

2

你可能需要進行urlencode要傳遞的查詢字符串參數;在這裏,至少「Main Page」需要編碼- 沒有這種編碼,我也得到了400錯誤

如果你試試這個,應該更好地工作(注意是%20替代的空間)

$url='http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Main%20Page'; 
$str = file_get_contents($url); 
var_dump($str); 

有了這個,我得到的頁面的內容。


一個解決方案是使用urlencode,所以你不必自己編碼:

$url='http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=' . urlencode('Main Page'); 
$str = file_get_contents($url); 
var_dump($str);