Simple HTML DOM Parser: how to read the value of the selected option

user1670164 picture user1670164 · Jun 16, 2013 · Viewed 9.1k times · Source

I have this HTML piece of code already read into $html. I had extracted some correct information, but I'm stuck getting the selected option value of a select.

<select name="a" id="selstart">
  <option value="00">Jan</option>
  <option value="01">Feb</option>
  <option value="02">Mar</option>
  <option value="03">Apr</option>
  <option value="04">May</option>
  <option value="05">Jun</option>
  <option selected value="06">Jul</option>
  <option value="07">Aug</option>
  <option value="08">Sep</option>
  <option value="09">Oct</option>
  <option value="10">Nov</option>
  <option value="11">Dec</option>
</select>

and need to extract the value "06" into a variable.

I tried:

foreach($html->find('select') as $element) {
    if ($element->id == 'selstart')
    {
        $v =  $element->find('option selected',0)->value . '</br>'; 
    }
}

and many other combinations following the idea found in php , simple_html_dom.php, get selected option but did not work.

Any ideas?

Answer

Antony picture Antony · Jun 16, 2013

Use element[attr] to select elements with the specified attribute.

$v =  $element->find('option[selected]', 0)->value . '</br>';