从URL中检索数据并保存在PHP中 [英] Retrieve data from url and save in php
问题描述
我正在尝试从php中获取内容的文件中检索html,然后将其保存到php文件中,以便可以将其包含到我的主页中.
I am trying to retrieve the html from file get contents in php then save it to a php file so I can include it into my homepage.
不幸的是,我的脚本没有将数据保存到文件中.我还需要每天写入一次此数据,因为它将通过cron作业进行设置.
Unfortunately my script isn't saving the data into the file. I also need to verwrite this data on a daily basis as it will be setup with a cron job.
有人可以告诉我我要去哪里了吗?我只是在学习php:-)
Can anyone tell me where I am going wrong please? I am just learning php :-)
<?php
$richSnippets = file_get_contents('http://website.com/data');
$filename = 'reviews.txt';
$handle = fopen($filename,"x+");
$somecontent = echo $richSnippets;
fwrite($handle,$somecontent);
echo "Success";
fclose($handle);
?>
推荐答案
几件事,
http://website.com/data
收到404错误,它不存在.
http://website.com/data
gets a 404 error, it doesn't exist.
将代码更改为
$site = 'http://www.google.com';
$homepage = file_get_contents($site);
$filename = 'reviews.txt';
$handle = fopen($filename,"w");
fwrite($handle,$homepage);
echo "Success";
fclose($handle);
删除$somecontent = echo $richSnippets;
它没有任何作用.
如果您具有适当的权限,它应该可以正常工作.
if you have the proper permissions it should work.
请确保您指向现有网页.
Be sure that your pointing to an existing webpage.
修改
启用cURL后,您可以使用以下功能
When cURL is enabled you can use the following function
function get_web_page( $url ){
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
curl_close( $ch );
return $content;
}
现在更改
$homepage = file_get_contents($site);
进入
$homepage = get_web_page($site);
这篇关于从URL中检索数据并保存在PHP中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!