简体   繁体   中英

php , simple_html_dom.php, get selected option

I have a html block like this :

$localurl = '
<select name="cCountry" id="cCountry" style="width:200" tabindex="5">

<option value="251">Ascension Island</option>
<option selected="selected" value="14">Australia</option>
<option value="13">Austria</option>
';

I'm trying to extract the selected value in this case "Australia" using simple_html_dom ( http://simplehtmldom.sourceforge.net/ ). So far I have build a function but is not working :

//extract the selected value

function getValue_selected($value, $localurl)
{
  $html = file_get_html($localurl);
  $i = 0;
   foreach ($html->find('select[option selected="selected"]') as $k => $v) {
     if ($v->name == $value) {
   $shows[$i]['Location'] = $v->value;
   }

   }
$value = $shows[$i]['Location'];
$html->clear();
unset($html);
return $value;
}

  $selected_value = getValue_selected('cCountry', $localurl)

An alternative such QueryPath would be accepted too .

正确的答案是:

$html->find('#cCountry',0)->find('option[selected=selected]',0);

My guess is that you're trying to access $shows when it is defined outside of the function. If this is the problem, you either need to put global $shows; at the top of the func, or, better still, modify the signature to pass it in. Something like:

getValue_selected($value, $localurl, &$shows)
{/* your function here */ }

getValue_selected($val1, $val2, $shows);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM