【问题标题】:Get text from div list to PHP array从 div 列表中获取文本到 PHP 数组
【发布时间】:2015-07-15 06:25:06
【问题描述】:

这是我的字符串。

$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>
';

从这个 html 获取数据并添加到 PHP 数组的最佳方法是什么? 我想收到:

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

【问题讨论】:

    标签: php html web-crawler


    【解决方案1】:

    使用DOMDocumentDOMXpath解析html并获取内容。
    然后,您可以在 : 上拆分它们并将它们添加到数组中。
    像这样的东西 -

    $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);
    

    这个输出 -

    array(4) {
      'foo' =>
      string(3) "bar"
      'name' =>
      string(5) "value"
      'color' =>
      string(3) "red"
      'count' =>
      string(1) "1"
    }
    

    【讨论】:

      【解决方案2】:
      var arr = [];
      $('.item').each(function(){
      
         var asdf = $(this).text();
         var qwerty = asdf.split(":");
            arr.push(qwerty['0'] + ' =>' + qwerty['1']); 
      });
      
      alert(arr);
      

      希望这对你有帮助.. =)

      【讨论】:

        【解决方案3】:

        您可以使用 SimpleXML 做到这一点。为此,您需要编写如下代码:

        <?php
        $html='<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>';
        
        $xml = new SimpleXMLElement($html);
        
        $result = $xml->xpath('//div[@id="list"]');
        $items = array();
        foreach($result AS $arrKeys => $arrValue){
                foreach($arrValue AS $innerValue){
                        list($key,$value) = explode(":",$innerValue);
                        if(!empty($value)){
                                $items[$key] = $value;
                        }
                }
        
        }
        
        print_r($items);
        ?>
        

        这是你想要的一步一步的代码。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-09-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-01
          • 2014-12-11
          • 1970-01-01
          相关资源
          最近更新 更多