简体   繁体   English

PHP 警告:file_get_contents

[英]PHP Warning: file_get_contents

So 2 days ago I got this message:所以2天前我收到了这条消息:

PHP Warning: file_get_contents( http://example.com ): failed to open stream: Connection timed out in /home/server/map/index.php on line 30 PHP 警告:file_get_contents( http://example.com ):无法打开流:第 30 行 /home/server/map/index.php 中的连接超时

This is what I've on line 29 and 30:这是我在第 29 和 30 行的内容:

$url = 'http://example.com';

$string = file_get_contents($url);

The fun part is that I can see the external content on my local host.有趣的是,我可以在本地主机上看到外部内容。 But not when I upload it to the server.但是当我将它上传到服务器时不会。 Then I can only see the html + css included in the index.php file.然后就只能看到index.php文件中包含的html+css了。

What I'm trying to do is to get all the available objects from the external website and post them on my website.我想要做的是从外部网站获取所有可用对象并将它们发布到我的网站上。

I've done it with a several other pages.我已经用其他几个页面完成了。 But now encountered problems with some of them.但是现在遇到了其中的一些问题。

Anyone here who has any exemepl on how I can solve it with php.这里的任何人都有关于我如何用 php 解决它的任何例子。 Possibly a completely different solution?可能是一个完全不同的解决方案?

You can use the file_get_contents function remotely, but many hosts don't allow this.您可以远程使用file_get_contents函数,但许多主机不允许这样做。 If you must use file_get_contents method, try to change default_socket_timeout option in PHP configuration in file php.ini or before your code insert:如果您必须使用file_get_contents方法,请尝试在文件php.ini或在代码插入之前更改 PHP 配置中的default_socket_timeout选项:

ini_set('default_socket_timeout', 900); // 900 Seconds = 15 Minutes

This should help with connection timed out.这应该有助于连接超时。 But I would recommend using some PHP frameworks or just CURL: Client URL Library但我建议使用一些 PHP 框架或仅使用 CURL:客户端 URL 库

For example:例如:

function get_data($url) {   
    $ch = curl_init();  
    $timeout = 900; // 900 Seconds = 15 Minutes 
    curl_setopt($ch, CURLOPT_URL, $url);    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);     
    $data = curl_exec($ch);     
    curl_close($ch);    
    return $data; 
}

The Usage:用法:

$returned_content = get_data('http://www.angelaget.se/till-salu/');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM