dongyan7950 2018-04-20 06:22
浏览 38
已采纳

PHP:Simple DOM Parser如何迭代这个html代码

<div id="score">
               <div class="name"><span style="width:68%">A</span></div>
                   <span class="roll">1</span>    

                <div class="name"><span style="width:60%">B</span></div>
                   <span class="roll">2</span>       

                 <div class="name"><span style="width:56%">C</span></div>
                   <span class="roll">3</span>          
 </div>

i want to iterate over each span of div.name but i am not getting to next span.roll tag I have used this code yet and also check the condition if A is available then 1 display and same as above name to check.

<?php
include("simple_html_dom.php");
$obj = new simple_html_dom();

 foreach ($obj->find('div[id=score]') as $factor)
    {
         $item = $factor->find('div[class=name] span')->plaintext;

          if(trim($item) == 'A')
          { 
             $a = $factor->find('span[class=roll]',0)->plaintext;
          }
          if(trim($item) == 'B')
          { 
            $b = $factor->find('span[class=roll]',1)->plaintext;
          }
          if(trim($item) == 'C')
          { 
             $c = $factor->find('span[class=roll]',2)->plaintext;
          }
           $final_array['overalldata'] = array
           (
            'a'=> $a,
            'b' => $b,
            'c' => $c,

            );
    }
   print_r($final_array);
   die;


?>

Any body having any idea please help to sort it out. Thanks

  • 写回答

1条回答 默认 最新

  • donglian4464 2018-04-20 06:36
    关注

    As an alternative, since you're targeting that ID, you don't need to have a foreach on the parent element, just get it outright.

    Then you apply the foreach on its children, getting the names and rolls.

    Here's the idea:

    $final_array['overalldata'] = null; // initialize
    $factor = $obj->find('div[id=score]', 0); // get the parent
    foreach ($factor->find('div[class=name]') as $item) { // each item of the parent
        $name = $item->find('span', 0)->innertext; // get the name
        $roll = $item->next_sibling()->innertext; // get the next sibling which is the roll
        $final_array['overalldata'][$name] = $roll; // and assign it (push it inside the array)
    
    }
    print_r($final_array);
    

    So basically, to get the name just target the child inside each div, and then, to target the roll (which is the sibling of each div), just use ->next_sibling() method.

    Sidenote: If I were you, I'd stick to DOM. It's already built-in inside PHP, no need to include any third party libraries.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分