如何从PHP调用网站服务?

时间:2012-07-20 04:00:55

标签: php web-services callback file-get-contents http-get

我的问题如下,我的服务器上有一个EmailReports.php用于发送电子邮件,如EmailReports.php?who = some@gmail.com& what = 123456.pdf

我无法修改EmailReports.php,因为它属于一个不同的项目,它会立即发送一封电子邮件,并且已被QA团队和所有这些东西批准。

现在,在一个不同的LookReports.php上我需要提供一个服务,比如“发给我我收到的报告”,只需调用EmailReports.php即可轻松执行,问题是,我该怎么做才能通过PHP码?所以它会自动调用另一个PHP。

我尝试过没有成功:

$stuff = http_get("http://...<the url here>");

$stuff =  file_get_contents("http://...<the url here>");

我正在考虑导入EmailReports.php,但由于没有功能,它似乎不对,它会自动发送电子邮件。

或者我可以复制EmailReports.php代码,但这违反了QA政策,因为需要额外的测试。

你可以指导一下吗?

提前致谢。

1 个答案:

答案 0 :(得分:6)

您可以使用Curl请求从任何网站检索信息(xml / html / json / etc)。

什么是CURL? (简答)

  

PHP有一个非常强大的调用库,专门用于安全地从远程站点获取数据。它被称为CURL。

来源:PHP, CURL, and YOU!

PHP中的卷曲函数示例

/* gets the data from a URL */
function get_data($url)
{
 if(function_exists('curl_init')){
 $ch = curl_init();
 $timeout = 5;
 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;
 } else 'curl is not available, please install';
 }

来源:Download a URL’s Content Using PHP cURL

  

或者,您可以使用file_get_contents执行当前正在执行的操作,但许多主机不允许这样做。 (沃尔什,2007年)

用法

<?php
$mydata = get_data('http://www.google.co.nz');
echo '<pre>';
print_r($mydata); //display the contents in $mydata as preformatted text
echo '</pre>';
?>

尝试使用其他网站对其进行测试,因为在执行curl之后,google通常会返回404 request(这是预期的)。