开发者

How to parse web form fields with xPath?

开发者 https://www.devze.com 2023-02-04 10:55 出处:网络
In order t开发者_运维技巧o retrieve name/value pairs.This should do it: $dom = new DOMDocument;

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

精彩评论

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

关注公众号