douhu1990 2015-07-15 06:25
浏览 11
已采纳

从div列表获取文本到PHP数组

Here is my string.

$list = '
<div id="list">
   <div class="item">foo: bar</div>
   <div class="item">name: value</div>
   <div class="item">color: red</div>
   <div class="item">count: 1</div>
</div>
';

How is the best way to get data from this html and add to PHP array? I would like receive:

$items = array('foo' => 'bar', 'name' => 'value', 'color' => 'red', 'count' => 1);
  • 写回答

3条回答 默认 最新

  • doutiao2540 2015-07-15 06:48
    关注

    Use DOMDocument and DOMXpath to parse the html and get the contents.
    You can then split them on : and add them to an array.
    Something like this -

    $str = <<<EOF
    <div id="list">
       <div class="item">foo: bar</div>
       <div class="item">name: value</div>
       <div class="item">color: red</div>
       <div class="item">count: 1</div>
    </div>
    EOF;
    
    //Parse the html data
    $dom = new DOMDocument;
    $dom->loadHTML($str);
    
    $xpath = new DOMXpath($dom);
    
    //Get only those divs which have class=item
    $div_list = $xpath->query('//div[@class="item"]');
    
    $content_arr = []; 
    foreach($div_list as $d){
         $c = explode(": ", $d->nodeValue);
         $content_arr[$c[0]] = $c[1];
    }
    
    var_dump($content_arr);
    

    This outputs -

    array(4) {
      'foo' =>
      string(3) "bar"
      'name' =>
      string(5) "value"
      'color' =>
      string(3) "red"
      'count' =>
      string(1) "1"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?