2

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

1 Answer 1

2

You could use XPath:

Getting DOM elements by classname

Get Element ByTag Name

Using PHP to get DOM Element

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

4
  • Those links are a bit too generic and RTFM, none of them pertains to a <table> example.
    – mario
    Oct 9, 2012 at 15:27
  • 1
    Under the last Link is a complete example. And yes its a short hint. When you want to learn something you should think about and try it out or not? Oct 9, 2012 at 15:29
  • We already have a few thousand cursory answers on this topic, as you remarked yourself.
    – mario
    Oct 9, 2012 at 15:32
  • Hey i'am not so fast ;) when i post some code it should be correct. But the most of the informations are on the related sites. Oct 9, 2012 at 15:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.