0

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 .

Michael
  • 6,377
  • 14
  • 59
  • 91
  • Suggested third party alternatives to [SimpleHtmlDom](http://simplehtmldom.sourceforge.net/) that actually use [DOM](http://php.net/manual/en/book.dom.php) instead of String Parsing: [phpQuery](http://code.google.com/p/phpquery/), [Zend_Dom](http://framework.zend.com/manual/en/zend.dom.html), [QueryPath](http://querypath.org/) and [FluentDom](http://www.fluentdom.org). – Gordon Jun 26 '11 at 13:13
  • @Gordon How can I get it with QueryPath ? – Michael Jun 26 '11 at 13:21

2 Answers2

2

the right answer is:

$html->find('#cCountry',0)->find('option[selected=selected]',0);
kleopatra
  • 51,061
  • 28
  • 99
  • 211
StanleyD
  • 2,308
  • 22
  • 20
1

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);
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
  • Originally I made the function to get hidden inputs : foreach ($html->find('input[type="hidden"]') as $k => $v) { . I could set the input name as $value . (e.g if there is I call the function getValue_selected('postingID', $localurl) which retrieves the value "98765" from the html content ) . Now I've tried to modify it to make it work on "select" input types as you can see above but doesn't seem to work . – Michael Jun 26 '11 at 13:43
  • 2
    I still say you're trying to access a variable which is undefined in scope. Have you tried adding a variable `$select = array();` to the inside of the function? – cwallenpoole Jun 26 '11 at 13:53