PHP 如何使用 curl 打开多个源? [英] PHP How can I open several sources using curl?

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

问题描述

我有一些代码可以获取站点 1 的 json 内容,但我还需要获取站点 2 的内容.我应该为 site2 再次重写所有这些行吗?或者我可以在 curl_setopt 中再添加一个 URL?

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

推荐答案

你可以创建一个类似

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

并用

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天全站免登陆