使curl获得最终的url并将其用于另一个函数

时间:2013-05-04 17:15:20

标签: php curl

我的网址包含此示例的变量:http:// remotesite.com/index1.php?option=com_lsh&view=lsh&event_id=149274&tid=372536&channel=0

此网址重定向到http://remotesite.com/static/popups/xxxxxxxxxxx.html

xxxxxxxxxxx是第一个链接的变量,event_id = 149274,tid = 372536,channel = 0

然后xxxxxxxxxxx = 1492743725360,链接将是:

http://remotesite.com/static/popups/1492743725360.html

如何通过链接http:// remotesite.com/index1.php?option=com_lsh&view=lsh&event_id=149274&tid=372536&channel=0

在php中自动获取此链接

然后我将使用curl函数获取源代码1492743725360.html

使用:

<?php
    //Get the url
    $url = "http:// remotesite.com/static/popups/1492743725360.html";

    //Get the html of url
    function get_data($url) 
    { 
       $ch = curl_init();
       $timeout = 5;
       //$userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US)AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.X.Y.Z Safari/525.13.";
       $userAgent = "IE 7 – Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)";
      curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
      curl_setopt($ch, CURLOPT_FAILONERROR, true);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($ch, CURLOPT_AUTOREFERER, true);
      curl_setopt($ch, CURLOPT_TIMEOUT, 10);
      curl_setopt($ch,CURLOPT_URL,$url);
      curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
      curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
      $data = curl_exec($ch);
      curl_close($ch);
      return $data;

    }

    $html = file_get_contents($url);
    echo $html;
?>

2 个答案:

答案 0 :(得分:0)

使用名为parse_url()的函数;第一个参数是整个URL。这将返回一个解析了URL的数组,您需要的部分是位于数组键'query'上的参数。 IE:

$parsedURL = parse_url($URL);

然后,使用parse_str()函数将数组键'query'作为第一个值传递,并将第二个值传递给存储结果的值。 IE:

parse_str($parsedURL['query'], $result);

然后,打印$ result将为您提供:

Array
(
     [option] => com_lsh
     [view] => lsh
     [event_id] => 149274
     [tid] => 372536
     [channel] => 0
)

请参阅http://php.net/manual/en/function.parse-url.phphttp://www.php.net/manual/en/function.parse-str.php

答案 1 :(得分:0)

$url = 'http://remotesite.com/index1.php?option=com_lsh&view=lsh&event_id=149274&tid=372536&channel=0';
$parsed = parse_url( $url );
parse_str( $parsed['query'], $data );
echo $newurl = 'http://remotesite.com/static/popups/'.
               $data['event_id'].$data['tid'].$data['channel'].
               '.html';

输出:

http://remotesite.com/static/popups/1492743725360.html