Reputation: 3
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);
Upvotes: 0
Views: 1050
Reputation: 21681
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.
Upvotes: 0
Reputation: 2439
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.. =)
Upvotes: 0
Reputation: 5473
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"
}
Upvotes: 2