PHP如何使用curl我打开几个来源是什么? [英] PHP How can I open several sources using curl?

查看:109
本文介绍了PHP如何使用curl我打开几个来源是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些code得到的站点1 JSON内容,但我还需要获得一个SITE2的内容。我要再次重写所有这些线路的站点2?或者,也许我可以再加上一个网址的 curl_setopt

  $ CH = curl_init();
curl_setopt($ CH,CURLOPT_URLhttp://site1.com);
curl_setopt($ CH,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ CH,CURLOPT_HEADER,0);
$ outputJson = curl_exec($ CH);
如果($ outputJson === FALSE){
    回声对不起,这个服务是当前不可用:。 curl_error($ CH);
}


解决方案

您可以创建一个像

函数

 函数GET_DATA($网址)
{
     $ CH = curl_init();
     curl_setopt($ CH,CURLOPT_URL,$网址);
     curl_setopt($ CH,CURLOPT_RETURNTRANSFER,1);
     curl_setopt($ CH,CURLOPT_HEADER,0);
     $ outputJson = curl_exec($ CH);
     如果($ outputJson === FALSE){
        回声对不起,这个服务是当前不可用:。 curl_error($ CH);
     }
     返回$ outputJson;
 }

和与调用它

  GET_DATA(http://blah.com);
GET_DATA(http://blah1.com);

这可能不是一个最佳的解决方案,但对于简单的实例shuould工作

I have some code to get json content of a site1 but I also need to get content of a site2. Should I rewrite all these lines again for the site2? Or maybe I can add one more URL in the curl_setopt?

$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);
}

解决方案

You can create a function like

function get_data($url)
{
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL,$url);
     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);
     }
     return $outputJson;
 }

and call it with

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

This might not be an optimal solution but shuould work for simple instances

这篇关于PHP如何使用curl我打开几个来源是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆