Simple html dom - how get dt/dd elements to array? [duplicate]

Deadly 提交于 2019-12-07 00:14:24
René Höhle

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!