开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜