In order to retrieve name/value pairs.
2
-
So you have an HTML document that you want to parse?Felix Kling– Felix Kling2011-01-12 00:29:19 +00:00Commented Jan 12, 2011 at 0:29
-
xPath is useful to parse XML, you usually don't need it for web form fields unless you want to parse XML entered into a textarea. Please be more specific.Damien– Damien2011-01-12 00:33:46 +00:00Commented Jan 12, 2011 at 0:33
Add a comment
|
1 Answer
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[]).