简体   繁体   中英

Get text from div list to PHP array

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

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"
}
var arr = [];
$('.item').each(function(){

   var asdf = $(this).text();
   var qwerty = asdf.split(":");
      arr.push(qwerty['0'] + ' =>' + qwerty['1']); 
});

alert(arr);

hope this helps you.. =)

You can do it with SimpleXML. And for that you need to code like this:

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

This is step by step code which is as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM