php , simple_html_dom.php, get selected option

2020-05-06 17:06发布

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 .

2条回答
做自己的国王
2楼-- · 2020-05-06 17:24

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);
查看更多
Lonely孤独者°
3楼-- · 2020-05-06 17:45

the right answer is:

$html->find('#cCountry',0)->find('option[selected=selected]',0);
查看更多
登录 后发表回答