加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP如何使用curl打开几个源?

发布时间:2020-12-13 22:02:39 所属栏目:PHP教程 来源:网络整理
导读:我有一些代码来获取site1的json内容,但我还需要获取site2的内容.我应该为site2重新编写所有这些行吗?或者我可以在curl_setopt中再添加一个URL? $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,"http://site1.com");curl_setopt($ch,CURLOPT_RETURNTRANSF
我有一些代码来获取site1的json内容,但我还需要获取site2的内容.我应该为site2重新编写所有这些行吗?或者我可以在curl_setopt中再添加一个URL?

$ch = curl_init(); 
curl_setopt($ch,CURLOPT_URL,"http://site1.com");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HEADER,0);
$outputJson = curl_exec($ch);
if ($outputJson === FALSE) {
    echo 'Sorry,This service is currently unavailable: '. curl_error($ch);
}

解决方法

你可以创建一个像这样的函数

function get_data($url)
{
     $ch = curl_init(); 
     curl_setopt($ch,$url);
     curl_setopt($ch,1);
     curl_setopt($ch,0);
     $outputJson = curl_exec($ch);
     if ($outputJson === FALSE) {
        echo 'Sorry,This service is currently unavailable: '. curl_error($ch);
     }
     return $outputJson;
 }

并称之为

get_data("http://blah.com");
get_data("http://blah1.com");

这可能不是最佳解决方案,但应该适用于简单的实例

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读