我有一些代码来获取site1的json内容,但我还需要获取site2的内容。我应该为site2重新编写所有这些行吗?或者我可以在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);
}
答案 0 :(得分:6)
您可以创建类似
的功能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");
这可能不是最佳解决方案,但应该适用于简单实例
答案 1 :(得分:4)
使用多个网址卷曲可以获得更好的性能。 见: http://php.net/manual/en/function.curl-multi-exec.php
并且:
答案 2 :(得分:1)
您可能想尝试遍历不同的网站:
$aSites = array("http://site1.com","http://site2.com");
for($x=0; $x<count($aSites); $x++){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$aSites[$x]);
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);
}
}
答案 3 :(得分:1)
<?
$url1 = "http://site1.com";
$url2 = "http://site2.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$outputJson = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, $url2);
$outputJson2 = curl_exec($ch);
curl_close($ch);
if ($outputJson === FALSE || $outputJson2 === FALSE) {
echo 'Sorry, This service is currently unavailable: '. curl_error($ch);
}
?>