PHP DOM - 通过选择名称获取所有选项值

时间:2017-02-20 07:47:32

标签: php dom

我需要得到"选项"来自网站的价值观。但是有多个选择"。我如何获得"选项"值由"选择名称"价值。 (通过select name = ctl02 $ dlOgretimYillari获取所有选项值)

<select name="ctl02$dlOgretimYillari" onchange="javascript:setTimeout('__doPostBack(\'ctl02$dlOgretimYillari\',\'\')', 0)" id="ctl02_dlOgretimYillari" class="NormalBlack">
            <option selected="selected" value="-40">2016-2017</option>

        </select>

我的代码:

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$options_value = array();
$options_name = array();
$options_selected = array();
foreach($dom->getElementsByTagName('option') as $option) {
    array_push($options_value, $option->getAttribute('value'));
    array_push($options_selected, $option->getAttribute('selected'));
    array_push($options_name, $option->nodeValue);
}

2 个答案:

答案 0 :(得分:1)

  

通过选择name = ctl02 $ dlOgretimYillari

获取所有选项值

使用DOMXPath::query方法的解决方案:

$content = '<select name="ctl02$dlOgretimYillari" onchange="javascript:setTimeout(\'__doPostBack(\'ctl02$dlOgretimYillari\',\'\')\', 0)" id="ctl02_dlOgretimYillari" class="NormalBlack">           <option selected="selected" value="-40">2016-2017</option>        </select>';

$doc = new DOMDocument();
libxml_use_internal_errors();
$doc->loadXML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));

$xpath = new DOMXPath($doc);
$nodes = $xpath->query("//select[@name='ctl02\$dlOgretimYillari']/option/@value");

// outputting first option value
print_r($nodes->item(0)->nodeValue);

输出:

-40

对于其他条件:如何获取选项文本的值?

...
$nodes = $xpath->query("//select[@name='ctl02\$dlOgretimYillari']/option/text()");
...

答案 1 :(得分:0)

@RomanPerekhrest的回答肯定解决了最初的问题!

但是对于我来说,我需要获取所有 selected 值,因此这是遇到相同问题的任何人的解决方案:

$nodes = $xpath->query("//select[@name='ctl02\$dlOgretimYillari']/option[@selected]/@value");

// Printing
foreach ($nodes as $node) {
    print_r($node->nodeValue);
}