2016-03-08 190 views
0

我想编写一个连接到维基百科URL并获取维基百科文章内容的php函数。我使用cURL与PHP。我指的是这个blog与维基百科页面卷曲php

问题是:该函数没有看到url的内容并返回错误。

这是我的代码:

<?php 
$wikipediaURL = 'http://fr.wikipedia.org/wiki/Megadeth'; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $wikipediaURL); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_USERAGENT, 'Le blog de Samy Dindane (www.dinduks.com)'); 
$resultat = curl_exec ($ch); 
curl_close($ch); 
$wikipediaPage = new DOMDocument(); 
$wikipediaPage->loadHTML($resultat); 
foreach($wikipediaPage->getElementsByTagName('div') as $div){ 
if($div->getAttribute('id') == "bodyContent"){ 
    $description = '<p>' . $div->getElementsByTagName('p')->item(0)->nodeValue. '</p>'; 
    $description = preg_replace('/\[[0-9]*\][,]|\[[0-9]*\]/', '', $description); 
    echo $description; }} 
?> 

这是错误消息:

警告:DOM文档:: loadHTML():作为输入 c供给空字符串:\瓦帕\ WWW \ Project1 \ wiki5.php 12行

我使用其他代码示例具有相同的功能,它不能只与维基百科url一起使用。

请任何帮助! 感谢

+0

你不检查,如果卷曲电话竟是成功。检查[我的答案的另一个问题](http://stackoverflow.com/questions/8227909/curl-exec-always-returns-false/13311209#13311209)找出如何诊断呼叫。 –

+1

你没有使用'wikipedia' api。我认为他们阻止空白请求。 https://www.mediawiki.org/wiki/API:Main_page – chris85

+0

不会file_get_contents的作品? $ wikipediaURL ='http://fr.wikipedia.org/wiki/Megadeth'; $ tmp = file_get_contents($ wikipediaURL); echo $ tmp; – SamyQc

回答

0

只需添加CURLOPT_FOLLOWLOCATION选项,您的代码将作品:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $wikipediaURL); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);          # <---- 
curl_setopt($ch, CURLOPT_USERAGENT, 'Le blog de Samy Dindane (www.dinduks.com)'); 
$resultat = curl_exec ($ch); 
curl_close($ch); 
+0

我添加CURLOPT_FOLLOWLOCATION,它给了我相同的结果空字符串作为输入提供。 – Adem

+0

你可以在别处使用cURL吗?我已经测试过它,它适用于我 – fusion3k

+0

的记录:试着用'echo file_get_contents($ wikipediaURL);' – fusion3k