2013-03-14 150 views
1

我正在嘗試使用MediaWiki獲取維基百科頁面(來自特定類別)。爲此,我正在關注this教程清單3.列出類別中的頁面。我的問題是:如何在不使用Zend Framework的情況下獲取Wikipedia頁面?有沒有基於PHP的休息客戶端,而無需安裝?因爲Zend需要首先安裝他們的軟件包,並且需要一些配置......我不想完成所有這些工作。將維基百科API與其他客戶端一起使用

谷歌搜索和一些調查後,我發現了一個名爲cURL的工具,使用PHP的cURL也可以建立一個休息服務。我在執行休息服務真的很新,但已經試圖在PHP中實現的東西:

<?php 
    header('Content-type: application/xml; charset=utf-8'); 

    function curl($url) { 
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL, $url); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     $data = curl_exec($ch); 
     curl_close($ch); 
     return $data; 
    } 
    $wiki = "http://de.wikipedia.org/w/api.php?action=query&list=allcategories&acprop=size&acprefix=haut&format=xml"; 
    $result = curl($wiki); 
    var_dump($result); 
?> 

,但得到的結果的誤差。任何人都可以提供幫助嗎?

UPDATE:

This page contains the following errors: 
error on line 1 at column 1: Document is empty 
Below is a rendering of the page up to the first error. 
+0

如果你告訴我們錯誤是什麼,它可能會有所幫助。 – 2013-03-14 19:53:12

+0

@IlmariKaronen請看看問題的'update'部分。 – Dozent 2013-03-14 20:48:21

回答

0

對不起,這麼長時間回答,但遲到總比不到好...

當我在命令行中運行代碼,輸出我得到的是:

string(120) "Scripts should use an informative User-Agent string with contact information, or they may be IP-blocked without notice. 
" 

如此看來,問題是你撞到Wikimedia bot User-Agent policy從沒有告訴捲曲發送自定義User-Agent頭。爲了解決這個問題,請在該頁面的底部提供的意見,並添加線,如以下到腳本(旁邊的其他curl_setopt()話費):

$agent = 'ProgramName/1.0 (http://example.com/program; [email protected])'; 
curl_setopt($ch, CURLOPT_USERAGENT, $agent); 

詩篇。您可能也不想設置application/xml內容類型,除非您確定確定內容實際上是有效的XML。特別是,var_dump()的輸出將會是而不是是有效的XML,即使輸入是。

對於測試和開發,我建議從命令行運行PHP或使用text/plain內容類型。或者,如果您願意,請使用text/html並使用htmlspecialchars()對輸出進行編碼。


Ps。這是一個社區維基答案,因爲我意識到這個問題已經是asked and answered before