Possible Duplicate:
Get data only from html table used preg_match_all in php
HTML:
<div class="table">
<dl>
<dt>ID:</dt>
<dd>632991</dd>
<dt>Type:</dt>
<dd>NEW</dd>
<dt>Body Type:</dt>
<dd>Compact</dd>
</dl>
</div>
What's is the best way to get this using simple_html_dom in PHP:
PHP:
$option = array(
'id' => 632991,
'Type' => 'NEW',
'Body Type' => 'Compact'
);
René Höhle
You could use XPath:
Getting DOM elements by classname
Here are a lot of posts on Stackoverflow. Use the search here.
Edit:
<?php
$dom = new DOMDocument();
$dom->loadHTML('<div class="table">
<dl class="list">
<dt>ID:</dt>
<dd>632991</dd>
<dt>Type:</dt>
<dd>NEW</dd>
<dt>Body Type:</dt>
<dd>Compact</dd>
</dl>
</div>');
$nodes = $dom->getElementsByTagName('dl');
foreach ($nodes as $node) {
var_dump(getArray($node));
}
function getArray($node) {
$array = false;
if ($node->hasAttributes()) {
foreach ($node->attributes as $attr) {
$array[$attr->nodeName] = $attr->nodeValue;
}
}
if ($node->hasChildNodes()) {
if ($node->childNodes->length == 1) {
$array[$node->firstChild->nodeName] = $node->firstChild->nodeValue;
} else {
foreach ($node->childNodes as $childNode) {
if ($childNode->nodeType != XML_TEXT_NODE) {
$array[$childNode->nodeName][] = getArray($childNode);
}
}
}
}
return $array;
}
?>
The function getArray is from php.net
来源:https://stackoverflow.com/questions/12803228/simple-html-dom-how-get-dt-dd-elements-to-array