How to parse web form fields with xPath?
In order t开发者_运维技巧o retrieve name/value pairs.
This should do it:
$dom = new DOMDocument;
$dom->load('somefile.html');
$xpath = new DOMXPath($dom);
$data = array();
$inputs = $xpath->query('//input');
foreach ($inputs as $input) {
if ($name = $input->getAttribute('name')) {
$data[$name] = $input->getAttribute('value');
}
}
$textareas = $xpath->query('//textarea');
foreach ($textareas as $textarea) {
if ($name = $textarea->getAttribute('name')) {
$data[$name] = $textarea->nodeValue;
}
}
$options = $xpath->query('//select/option[@selected="selected"]');
foreach ($options as $option) {
if ($name = $option->parentNode->getAttribute('name')) {
$data[$name] = $option->getAttribute('value');
}
}
Depending on whether or not you have multiple forms in your HTML, you may want to pass the second argument to query() to differentiate them, and add an extra loop.
You will have to tweak it a bit if you use array keys (e.g.: yourfield[]
).
精彩评论