【问题标题】:how to get a webpage using php curl in xampp如何在xampp中使用php curl获取网页
【发布时间】:2014-05-15 03:45:09
【问题描述】:

我最近开始使用 PHP。为了获得一些网站内容,我使用以下代码。但是这段代码总是返回“Empty”。我正在使用 xampp 的 PHP 来运行此代码。

另外,我已经从 xampp/php/php.ini 文件中取消了对表达式“extension=php_curl.dll”的注释。

请帮我看看为什么它不返回网页内容? 还有如何从这些网页中获取具体数据?

这是我的代码:

<?php
$html=get_data('http://timesofindia.indiatimes.com/');
if (!empty($html))
    echo $html;
else
    echo "Empty";

function get_data($location){
    $ch = curl_init($location);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
    }
?>

我该怎么做?

【问题讨论】:

  • apaches 错误日志中是否有任何错误?还是 PHP?
  • 相同的代码在我的本地工作。所以你在 xampp 中的 CURL 设置有问题。确保在进行任何更改后重新启动 apache。
  • @Mahesh,此代码也适用于我的本地页面。但我的问题是我应该如何使用它来获取一些互联网网页??

标签: php html curl xampp


【解决方案1】:

您可以改用类似的东西(不带或带自定义上下文):

$url = 'http://timesofindia.indiatimes.com/';
$result = file_get_contents($url, false, $context);
echo ( $result ) ? $result : 'Empty';

http://php.net/file_get_contents

$opts = array('http' => 
                array(
                    'method'  => 'GET',
                    'timeout' => 15
                )
        );
$context = stream_context_create($opts);

【讨论】:

  • 感谢您的帮助,但这段代码也不起作用,它显示了一些错误。
  • 现在我可以查看我的本地 XAMPP 服务器文件的网页,但对于 google.com 等其他网站,它显示错误“无法解析主机 google.com。错误号 6”
  • @ash:你在你的 $url âla "http://" 中使用协议前缀吗?也许你想转储 $url 以确保它是正确的。另一个提示是尝试不使用 DNS 并使用 Google 提供的 IP。
  • 我按照你的建议做了同样的事情,但没有奏效。如果您还有其他技巧,请提出其他建议。
  • 我用ip地址代替了命名。还尝试使用和不使用前缀“http://”。您确定本地服务器(如 XAMPP)是否能够连接互联网以获取某些网页的内容?
猜你喜欢
  • 2020-08-09
  • 2010-11-23
  • 1970-01-01
  • 2014-01-22
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多