使用PHP发出get请求并将数据复制到服务器

使用PHP发出get请求并将数据复制到服务器,php,get,cron,request,Php,Get,Cron,Request,我想使用cronjob每60分钟发出一次GET请求,在我的web服务器上缓存一个RSS提要。MyHoster提供了一个web界面来创建cronjob,因此这应该很容易做到。由于我几乎没有使用php的经验,所以我对这一部分感到困惑。我的代码当前如下所示: <?php $response = http_get("http://www.target-url.com/feed.rss"); $myfile = fopen("rp.xml", "w") or die("Unable to open

我想使用cronjob每60分钟发出一次GET请求,在我的web服务器上缓存一个RSS提要。MyHoster提供了一个web界面来创建cronjob,因此这应该很容易做到。由于我几乎没有使用php的经验,所以我对这一部分感到困惑。我的代码当前如下所示:

<?php
$response = http_get("http://www.target-url.com/feed.rss");
$myfile = fopen("rp.xml", "w") or die("Unable to open file!");
fwrite($myfile, $response);
?>
HTTP/1.1 200 OK
Date: Wed, 28 Jan 2015 20:27:03 GMT
Content-Type: application/rss+xml;charset=utf-8
Connection: keep-alive
Set-Cookie: creid=1491575037291426898; expires=Thu, 31-Dec-37 23:55:55 GMT; domain=.target-url.com; path=/; httpOnly
X-Served-By-CC: s19lpay01
X-Cache-Control-Set-By: X-Set-Cache-TTL (300)
Cache-Control: public, max-age=300
Access-Control-Allow-Origin: *
Last-Modified: Wed, 28 Jan 2015 20:23:16 GMT
Content-Length: 10672
Edge-Control: max-age=300
X-Cache: HIT (13)
X-Served-By: RFCTC01
Accept-Ranges: bytes
X-Age: 227

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
{...rest of the xml}

这会将所有内容写入rp.xml,但也会写入标题,因此会得到无效的xml。rp.xml的内容如下所示:

<?php
$response = http_get("http://www.target-url.com/feed.rss");
$myfile = fopen("rp.xml", "w") or die("Unable to open file!");
fwrite($myfile, $response);
?>
HTTP/1.1 200 OK
Date: Wed, 28 Jan 2015 20:27:03 GMT
Content-Type: application/rss+xml;charset=utf-8
Connection: keep-alive
Set-Cookie: creid=1491575037291426898; expires=Thu, 31-Dec-37 23:55:55 GMT; domain=.target-url.com; path=/; httpOnly
X-Served-By-CC: s19lpay01
X-Cache-Control-Set-By: X-Set-Cache-TTL (300)
Cache-Control: public, max-age=300
Access-Control-Allow-Origin: *
Last-Modified: Wed, 28 Jan 2015 20:23:16 GMT
Content-Length: 10672
Edge-Control: max-age=300
X-Cache: HIT (13)
X-Served-By: RFCTC01
Accept-Ranges: bytes
X-Age: 227

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
{...rest of the xml}
HTTP/1.1200正常
日期:2015年1月28日星期三20:27:03 GMT
内容类型:应用程序/rss+xml;字符集=utf-8
连接:保持活力
设置Cookie:creid=1491575037291426898;expires=Thu,37年12月31日23:55:55 GMT;域=.target-url.com;路径=/;httpOnly
X-SERVIED-By-CC:s19lpay01
X-Cache-Control-Set-By:X-Set-Cache-TTL(300)
缓存控制:公共,最大使用年限=300
访问控制允许来源:*
最后修改:2015年1月28日星期三20:23:16 GMT
内容长度:10672
边缘控制:最大年龄=300
X缓存:命中(13)
X服务人:RFCTC01
接受范围:字节
X年龄:227
{…xml的其余部分}
您可以使用:

file_get_contents()是将文件内容读入字符串的首选方法。如果操作系统支持,它将使用内存映射技术来提高性能

注意:如果要使用特殊字符(如空格)打开URI,则需要使用urlencode()对URI进行编码


你做了什么来调试这个?尝试自己从CLI运行它。这样行吗?如果没有-对$response和$myfile执行var_dump(),以检查您是否确实从远程服务器获取数据,并检查您是否成功打开了文件资源。另外:您说没有创建“feed.rss”。如果您尝试编写“rp.xml”,您会想到这一点吗?我想这只是一个打字错误。好了,现在可以了。但是我只想要纯XML,而不是标题。我编辑了我的原始问题。如何自动删除标题?您可以使用file\u get\u contents()或curl。file\u get\u contents()完成了这项工作。谢谢@CamilStaps