mrdeveloper
mrdeveloper

Reputation: 55

PHP DOM - Get all option value by select name

I need to get "option" values from a site. But there are more than one "select". How do I get "option" values by "Select name" value . (get all option value by 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>

My Code :

$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);
}

Upvotes: 3

Views: 1480

Answers (2)

Thiago
Thiago

Reputation: 91

@RomanPerekhrest 's answer definitely solved the initial question!

But in my case I needed to get all the selected values, so here's the solution for anyone with the same problem:

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

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

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

get all option value by select name=ctl02$dlOgretimYillari

The solution using DOMXPath::query method:

$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);

The output:

-40

For additional condition: How do I get the value of the option text?

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

Upvotes: 1

Related Questions