使用html dom解析器时,foreach循环和php中的其他意外

时间:2017-05-18 06:43:00

标签: php html xpath simpledom

我编写了一个代码来使用html simple dom解析器,这里是:

<?php $opts = array(   'http'=>array( 
   'header'=>"User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53\r\n"   ) );
    $context = stream_context_create($opts);
    set_time_limit(0);
    include 'simple_html_dom.php';
    $lines = file('BQ.txt');
    foreach ($lines as $line_num => $line){
       $html = file_get_html($line, false, $context);
       if($html && is_object($html) && isset($html->nodes)){
          echo $line; 
       }
       echo "<ul>";
       foreach($html->find("h1[class='productname'],  div[class='productprice']") as $element ){
            if ($element) { } 
            echo "<li>".$element ->plaintext. "</li>";
       } else {
            echo "kosong" 
       }
        echo "</ul>"; 
     }
     $html->clear(); ?>

但它总是解析错误:语法错误,意外'其他'(T_ELSE) 我已经尝试了很多方法,但仍然没有解决方案,问题只是    其他{     回声“对不起空”    }

如果我在没有它的情况下运行脚本,它会完美运行

3 个答案:

答案 0 :(得分:0)

您的代码中存在语法错误。请将您的代码与以下内容进行比较:

<?php $opts = array(   'http'=>array( 
   'header'=>"User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53\r\n"   ) );
    $context = stream_context_create($opts);
    set_time_limit(0);
    include 'simple_html_dom.php';
    $lines = file('BQ.txt');
    foreach ($lines as $line_num => $line){
       $html = file_get_html($line, false, $context);
       if($html && is_object($html) && isset($html->nodes)){
          echo $line; 
       }
       echo "<ul>";
       foreach($html->find("h1[class='productname'],  div[class='productprice']") as $element ){
            if ($element) {
                echo "<li>".$element ->plaintext. "</li>";
            } else {
                echo "kosong" ;
            }
       }
        echo "</ul>"; 
     }
     $html->clear(); ?>

答案 1 :(得分:0)

  

Sytax错误:其他部分在每秒结束后开始,并在if条件内移动你的回声

          <?php $foreach ($lines as $line_num => $line){
           $html = file_get_html($line, false, $context);
           if($html && is_object($html) && isset($html->nodes)){
              echo $line; 
           }
           echo "<ul>";
           foreach($html->find("h1[class='productname'],  div[class='productprice']") as $element ){
                if ($element) { echo "<li>".$element ->plaintext. "</li>"; } 
                else {
                echo "kosong" 
               }
           } 
            echo "</ul>"; 
         }
    ?>

答案 2 :(得分:0)

主要问题在这里

if ($element) { } 
        echo "<li>".$element ->plaintext. "</li>";
   } else {
        echo "kosong" 
   }
    echo "</ul>"; 
 }
 $html->clear(); ?>

解决方案是......

f ($element) {
        echo "<li>".$element ->plaintext. "</li>";
   } else {
        echo "kosong" ;
   }
    echo "</ul>"; 
 }
 $html->clear();
}?>

解析得很好。

相关问题