我想填写一个表单字段并使用 CURL 提交它。该网页有许多已填写的表单字段,因此我不想触摸这些字段。
那么是否可以使用curl并仅填充必填字段并将其与已填充的所有其他字段一起提交?
最佳答案
完整演练(给定提供的 HTML 抓取文本)
要进行自定义,您只需将字段名称添加到 $fields_i_want
数组中,以指定您想要从下载的源文本中提取的所有文本字段值,并更改检索和提交位置的 URL。
此外,file_get_contents()
的更好替代方法是curl。您可以使用 this SO post 上的说明了解如何通过curl 检索远程文本。
// First, retrieve the remote source using file_get_contents()
$str = file_get_contents('http://www.example.com/');
$my_field_val = 'my_field_value';
$fields_i_want = array('audien', 'unifor');
$field_vals = array();
$field_string = '';
// Use DOM to parse the values you want from the form
$dom = new DOMDocument;
$dom->loadHTML($str);
// Get all the input field nodes
$inputs = $dom->getElementsByTagName('input');
// Iterate over the input fields and save the values we want to an array
foreach ($inputs as $input) {
$name = $input->getAttribute('name');
if (in_array($name, $fields_i_want)) {
$val = $input->getAttribute('value');
$field_vals[$name] = $val;
}
}
// append the field value we set ourselves to the list
$field_vals['my_field'] = $my_field_val;
foreach ($field_vals as $key => $val) {
$field_vals[$key] = urlencode($val)
}
// url-ify the data for the POST
foreach($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
// open connection
$ch = curl_init();
// POST the data to the form submission url
$submit_url = 'http://www.submitform.com';
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
// execute post (returns TRUE on success or FALSE on failure)
$result = curl_exec($ch);
// close connection
curl_close($ch);
关于php - 填写表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8419997/