为什么在第二次调用时,php“curl”功能无法正常工作?

时间:2015-11-19 07:10:32

标签: php php-curl

我第一次使用php Curl 这是我的代码:

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'http://huger.blog.ir/rss/');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$full = curl_exec($ch);
curl_close($ch);
$full = (string)$full;
$l = strpos($full,'</link>');
$start = strpos($full,'<link>',$l);
$end = strpos($full,'</link>',$l+2);
global $link;
$link = substr($full, $start , $end-$start);
$v = curl_init();
curl_setopt($v,CURLOPT_URL,$link);
curl_setopt($v,CURLOPT_RETURNTRANSFER,true);
$page = curl_exec($v);
curl_close($v);
echo $page;

$ch curl完成其工作并$link正确完成。 现在我认为我的第二个卷曲($v)不起作用。 有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

试试此代码

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'http://huger.blog.ir/rss/');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$full = curl_exec($ch);
curl_close($ch);
$full = (string)$full;
$l = strpos($full,'</link>');
$start = strpos($full,'<link>',$l);
$end = strpos($full,'</link>',$l+2);
global $link;
$link = substr($full, $start , $end-$start);
var_dump($link);
$v = curl_init();
curl_setopt($v,CURLOPT_URL,$link);
curl_setopt($v,CURLOPT_RETURNTRANSFER,true);
$page = curl_exec($v);
echo curl_error($v);
curl_close($v);
var_dump($page);

你可以看到你的网址前面有一个标签,如

string '<link>http://huger.blog.ir/1394/08/24/start' (length=43)

这导致了问题

答案 1 :(得分:0)

在这种情况下,如果我可以使用一个元素,我将该工作元素包装在functionclass中以便按原样重用。看看这是否是您正在寻找的:

function cURL($url = false,$settings = false)
    {
        $string =   (!empty($settings['toString']));
        $json   =   (!empty($settings['toJson']));

        $ch     =   curl_init();
        curl_setopt($ch,CURLOPT_URL,'http://huger.blog.ir/rss/');
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $response   =   curl_exec($ch);

        if($string)
            $response   =   (string) $response;
        elseif($json)
            $response   =   json_decode($response,true);

        curl_close($ch);
        return $response;
    }

function toLink($cURL = false)
    {
        $l      =   strpos($cURL,'</link>');
        $start  =   strpos($cURL,'<link>',$l);
        $end    =   strpos($cURL,'</link>',$l+2);
        $link   =   substr($cURL, $start , $end-$start);
        // As noted by @Hari Swaminathan, you have a <link> at the front,
        // so strip_tags will remove that
        return strip_tags($link);
    }

$link   =   cURL('http://huger.blog.ir/rss/',array("toString"=>true));

echo cURL(toLink($link));