Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP连接到MediaWiki API并检索数据_Php_Api_Service_Mediawiki_Mediawiki Api - Fatal编程技术网

PHP连接到MediaWiki API并检索数据

PHP连接到MediaWiki API并检索数据,php,api,service,mediawiki,mediawiki-api,Php,Api,Service,Mediawiki,Mediawiki Api,我注意到有一个问题与我的问题有些相似,只是c:。 让我解释一下:我对整个web服务实现非常陌生,因此我在理解上遇到了一些困难(特别是由于MediaWiki API手册含糊不清) 我希望在PHP(XML文件)中以字符串形式检索整个页面,然后在PHP中对其进行处理(我很确定还有其他更复杂的方法来解析XML文件,但不管怎样): 我试着做了$fp=fopen($url,'r')。它输出:HTTP请求失败!HTTP/1.0 400错误请求。API不需要密钥来连接它 您能否详细描述如何连接到API并以字符

我注意到有一个问题与我的问题有些相似,只是c:。 让我解释一下:我对整个web服务实现非常陌生,因此我在理解上遇到了一些困难(特别是由于MediaWiki API手册含糊不清)

我希望在PHP(XML文件)中以字符串形式检索整个页面,然后在PHP中对其进行处理(我很确定还有其他更复杂的方法来解析XML文件,但不管怎样):

我试着做了
$fp=fopen($url,'r')。它输出:
HTTP请求失败!HTTP/1.0 400错误请求
。API不需要密钥来连接它

您能否详细描述如何连接到API并以字符串形式获取页面

编辑:
该URL是
$URL=http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Main 页面'。我只想将文件的全部内容读入字符串以使用它。

连接到该API就像检索文件一样简单

只有在服务器启用了
fopen
wrappers的情况下,才能使用上述两个选项

否则,如果您的服务器已安装,您可以使用它

$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;

您可能需要对在查询字符串中传递的参数进行URL编码;在这里,至少“
主页
”需要编码——如果没有这种编码,我也会得到一个400错误

如果您尝试这样做,它应该会工作得更好(注意空格被
%20
替换):

有了这个,我得到了页面的内容


一个解决方案是使用,这样您就不必自己编码:

$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);

根据MediaWiki API文档,如果您在PHP请求中未指定用户代理,WikiMedia将使用4xx HTTP响应代码拒绝连接:


您可以尝试更新代码以添加该请求头,或者更改php.ini中的默认设置(如果您有编辑权限)。

您能再给我们看一点代码吗?非常感谢!您知道如何在本地apache上启用fopen包装器吗?请确保在php ini中允许\u url\u fopen=1。
$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;
$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);
$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);