0

我想我不明白。我试图解析一些 html 页面:

<select name="sel">
  <option value="val0">-please select me-</option>
  <option value="val1">some selection</option>
</select>

我使用 Simple_html_dom 类:

foreach($html->find('select') as $s) {
    if ($html->find('option',1) != false) {
      $tempoption = $html->find('option',1)->plaintext;
      echo $tempoption; //shows 'some selection'
    }
}

但是,如果我只是使用这一行:

$value='';
if ( $tempoption == 'some selection')
   $value='79';
echo $value; //doesn't shows anything (empty variable?)

//or this one :
if ( strcmp($tempoption, 'some selection'))
   $value='79';
echo $value; //Nope.
4

1 回答 1

0

我尝试了代码,就像你在那里一样,并$value最终得到 79。但我认为你的 HTML 必须比那个小片段更多。您的代码中最让我印象深刻的事情是您将条件包装在一个循环中,该循环遍历了 HTML 的所有选择,但您没有使用从循环中获得的单个选择元素,所以 foreach 循环似乎毫无意义..

看看这个:

foreach($html->find('select option') as $o) 
{
  $o_label = $o->plaintext;
  if($o_label=='some selection') echo 'PERFECT MATCH: '.$o_label."\n"; 
  else if(stripos($o_label, 'some selection')!==false) echo 'LOOSE MATCH: '.$o_label."\n"; 
  else echo 'DOES NOT MATCH: '.$o_label."\n";
}


当给定 HTML 时:

<select name="sel">
  <option value="val0">-please select me-</option>
  <option value="val1">1 some selection</option>
  <option value="val1">This does not match</option>
  <option value="val1">some selection</option>
  <option value="val1">Another non-matching label</option>
  <option value="val1">some selection 3</option>
  <option value="val1">One more that does not match</option>
  <option value="val1">4 SoME sElEcTIon 4</option>
</select>

输出将是:

DOES NOT MATCH: -please select me-
LOOSE MATCH: 1 some selection
DOES NOT MATCH: This does not match
PERFECT MATCH: some selection
DOES NOT MATCH: Another non-matching label
LOOSE MATCH: some selection 3
DOES NOT MATCH: One more that does not match
LOOSE MATCH: 4 SoME sElEcTIon 4
于 2011-11-04T17:29:32.813 回答