如何使用php从.ashx页面下载文件?

时间:2016-01-24 15:24:31

标签: php curl

我正在尝试从这个网址下载一个文件:http://www.roblox.com/Asset/BodyColors.ashx?userId=36377783

该页面返回webbrowser自动下载的文件。

我尝试过使用cURL:

<?php
$uid = 36377783;

$xUrl = "http://www.roblox.com/Asset/BodyColors.ashx?userId=".$uid;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $xUrl);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$xml = curl_exec($ch);
curl_close($ch);

echo $xml;

?>

但它会将我重定向到错误页面。

如何下​​载.ashx网址返回的文件?

(设置CURLOPT_USERAGENT不起作用。)

1 个答案:

答案 0 :(得分:1)

有重定向 - 我使用file_get_contents()(但为什么不卷曲)和$http_response_header

$uid = 36377783;

$xUrl = "http://www.roblox.com/Asset/BodyColors.ashx?userId=".$uid;

$opts = array(
  'http'=>array(
      'method'=>"GET",
      'follow_location' => true,
      'header'=>
        "Host: www.roblox.com\r\n" .
        "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0\r\n" .
        "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" .
        "Accept-Encoding: gzip, deflate\r\n" .
        "DNT: 1\r\n"

  )
);


$context = stream_context_create($opts);
$xml = file_get_contents($xUrl, false, $context);
#print_r($http_response_header);
$url_redirect = str_replace('Location: ',"",$http_response_header[5]);
#print $url_redirect;
$xml = file_get_contents($url_redirect);
#print_r($xml);
$roblox_responses = new SimpleXMLElement($xml);
print_r($roblox_responses);