我需要每天从我的本地服务器下载http://www.carriersoftwaredata.com/Login.aspx?file=FHWA的CSV文件。我的计划是执行一个运行php脚本的cron作业来执行此操作。但是,在允许下载文件之前,该页面需要输入用户名和密码。如果我在我的Web浏览器中访问此页面,请输入用户名和密码,然后提交表单,然后我的浏览器会显示一个Download对话框并开始下载该文件。如何使用PHP提交表单并从其他网站检索文件?
如何使用PHP提交表单并下载提供的文件?
这是我目前正在做的,以获得必要的$ _POST信息。
//url for fhwa db file
$fhwa_url = 'http://www.carriersoftwaredata.com/Login.aspx?file=FHWA';
//get the contents of the fhwa page
$fhwa_login = file_get_contents($fhwa_url);
//load contents of fhwa page into a DOMDocument object
$fhwa_dom = new DOMDocument;
if (!$fhwa_dom->loadhtml($fhwa_login))
{
echo 'Could not Load html for FHWA Login page.';
}
else
{
//create a post array to send back to the server - keys relate to the name of the input
$fhwa_post_items = array(
'__VIEWSTATE'=>'',
'Email'=>'',
'Password'=>'',
'__EVENTVALIDATION'=>'',
);
//create an xpath object
$xpath = new DOMXpath($fhwa_dom);
//iterate through the form1 form and find all inputs
foreach($xpath->query('//form[@name="form1"]//input') as $input)
{
//get name and value of input
$input_name = $input->getAttribute('name');
$input_value = $input->getAttribute('value');
//check if input name matches a key in the post array
if(array_key_exists($input_name, $fhwa_post_items))
{
//if the input name is Email or Password enter the defined email and password
switch($input_name)
{
case 'Email':
$input_value = $email;
break;
case 'Password':
$input_value = $pass;
break;
}//switch
//assign value to post array
$fhwa_post[$input_name] = $input_value;
}// if
}// foreach
}// if
这就是我如何提交表单 - 但它似乎并没有以我需要的方式工作。我希望stream_get_contents返回的内容是我想要下载的CSV文件的内容。
//get the url data and open a connection to the page
$url_data = parse_url($fhwa_url);
$post_str = http_build_query($fhwa_post);
//create socket
$fp = @fsockopen($url_data['host'], 80, $errno, $errstr, 30);
fputs($fp, "POST $fhwa_url HTTP/1.0\r\n");
fputs($fp, "Host: {$url_data['host']}\r\n");
fputs($fp, "User-Agent: Mozilla/4.5 [en]\r\n");
fputs($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-Length: ".strlen($post_str)."\r\n");
fputs($fp, "\r\n");
fputs($fp, $post_str."\r\n\r\n");
echo stream_get_contents($fp);
fclose($fp);
任何帮助是绝对赞赏。
喜克里斯 - 感谢您的帮助。我发现了一个不同的解决方案,无需使用cURL,但是如果我需要做类似的事情,肯定会看到这个。感谢您向我展示如何通过cURL发送帖子字段。 – jeremysawesome 2010-11-09 17:57:29