1

In order to retrieve name/value pairs.

2
  • So you have an HTML document that you want to parse? Commented 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. Commented Jan 12, 2011 at 0:33

1 Answer 1

2

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[]).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.