2016-09-06 62 views
1

我试图找到从源URL重定向的URL得到这个我使用下面的代码中找到重定向的URL ...使用curl

$url="http://www.idealo.fr/go/737821809.html?categoryId=12313&pos=1&price=499.99&productid=4716350&sid=26246&type=offer"; 
$ch = curl_init(); 
     $timeout = 0; 
     curl_setopt ($ch, CURLOPT_URL, $url); 
     curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
     curl_setopt($ch, CURLOPT_HEADER, TRUE); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); 

     $header = curl_exec($ch); 
     $retVal = array(); 
     $fields = explode("\r\n", preg_replace_callback ('/\x0D\x0A[\x09\x20]+/', ' ', $header)); 
     foreach($fields as $field) { 
      if(preg_match('/([^:]+): (.+)/m', $field, $match)) { 
       $match[1] = preg_replace_callback ('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1]))); 
       if(isset($retVal[$match[1]])) { 
        $retVal[$match[1]] = array($retVal[$match[1]], $match[2]); 
       } else { 
        $retVal[$match[1]] = trim($match[2]); 
       } 
      } 
     } 
echo '<pre>'; 
print_r($retVal); 
echo '</pre>'; 

if (isset($retVal['Location'])){ 
    echo $retVal['Location']; 
} else { 

    echo $_GET[$urlKey]; 
} 
curl_close($ch); 

现在,它返回我下面的输出.. 。

Array (
    [date] => Tue, 06 Sep 2016 15:34:27 GMT 
    [server] => idealoAppServer 
    [location] => http://track.effiliation.com/servlet/effi.redir?id_compteur=13087834&url=http://www.priceminister.com/offer/buy/1134677256/canon-eos-750d-appareil-photo-numerique.html 

    [content-type] => text/html; charset=UTF-8 
    [content-length] => 0 
    [set-cookie] => Array 
     (
      [0] => Array 
       (
        [0] => oop_mvp_2=A; domain=.idealo.fr; path=/; expires=Thu, 05-Dec-2016 15:34:27 GMT 
        [1] => ipcuid=01jo0lb800isrmzsx0; domain=.idealo.fr; path=/; expires=Mon, 27-Aug-2018 15:34:27 GMT 
       ) 

      [1] => icda=1; domain=.idealo.fr; path=/; expires=Wed, 06-Sep-2017 15:34:27 GMT 
     ) 

    [vary] => Accept-Encoding,User-Agent 
    [connection] => close) 

现在,从这个数组我只需要下面的输出...

http://www.priceminister.com/offer/buy/1134677256/canon-eos-750d-appareil-photo-numerique.html 

任何人都可以请帮我形成ARR唉,所以我只是得到的url只...我最近已升级到php7从PHP 5 ...是这可能是其中一个原因...

+0

您的'preg_replace_callback()'函数没有有效的回调。 –

回答

1

您可以使用parse_url解析您收到的网址location关键

$url_parse = parse_url($retVal['location']); 

之后,你会在$url_parse有somehing这样的:

array (
    'scheme' => 'http', 
    'host' => 'track.effiliation.com', 
    'path' => '/servlet/effi.redir', 
    'query' => 'id_compteur=13087834&url=http://www.priceminister.com/offer/buy/1134677256/canon-eos-750d-appareil-photo-numerique.html', 
) 

所以查询是query关键。现在,我们需要分析它,你中央社使用parse_str

parse_str($url_parse['query'], $output); 

现在在$output你会有这样的事情:

array (
    'id_compteur' => '13087834', 
    'url' => 'http://www.priceminister.com/offer/buy/1134677256/canon-eos-750d-appareil-photo-numerique.html', 
) 

所以你想要的网址是$output['url']

echo $output['url']; //here is the url that you want.