【问题标题】:Make get request and copy data to server with PHP使用 PHP 发出获取请求并将数据复制到服务器
【发布时间】:2015-01-28 20:13:59
【问题描述】:

我想使用 cronjob 每 60 分钟发出一次 GET 请求,以在我的网络服务器上缓存 RSS 提要。我的主机提供了一个 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);
?>

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

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}

【问题讨论】:

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

标签: php get cron request


【解决方案1】:

您可以改用file_get_contents()

string file_get_contents ( string $filename [, bool $use_include_path = false [, 
    resource $context [, int $offset = -1 [, int $maxlen ]]]] )

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

注意:如果您打开一个带有特殊字符(例如空格)的 URI,您需要使用 urlencode() 对 URI 进行编码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2014-09-26
    相关资源
    最近更新 更多