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

3

5

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?

Stephi answered 16/6, 2013 at 2:28 Comment(0)
S
7

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

$v =  $element->find('option[selected]', 0)->value . '</br>';
Sisson answered 16/6, 2013 at 3:5 Comment(0)
E
1

try this simple code

$element =  $html->find('#selectIDGoesHere',0)->find('option');     
    foreach($element as $elemen) {         
        echo "Display text:".($elemen->plaintext)."<br>"; 
        echo "value:".($elemen->value)."<br>";
    } 
Empressement answered 29/12, 2016 at 12:12 Comment(0)
A
0

Thank you, for your reply, if you want to set option values after reading the select you can do like this: First loaded the html select from another file for example, It is something like this:

<div>
<select id="select1">
</select>
</div>

Then you can do like this:

<?php 
$html=str_get_html($filename_or_method_to_the_html_content);
$products='<option></option>'.
          '<option val="1">Val 1</option>'.
          '<option val="2" selected="selected">Val 2</option>'.
          '<option val="3">Val 3</option>';
$html->find('select[id=select1]','0')->innertext=$products;
?>

It worked well for me ;)

Artifice answered 5/4, 2015 at 9:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.