首页 > 解决方案 > 如何使用 DOMparser/Xpath 在 div 下抓取 DL 的 DT 和 DD

问题描述

我正在尝试获取属于某个类的 DL 的 DT 和 DD,并尝试将它们放在一个 foreach 中。但面对一些麻烦,

<dl class="c-explain2">
        <dt>所在地</dt>
                <dd>
                    大阪府大阪市 北区天満1丁目25番1(地番)
                        <br>

这是我的代码;

$DOMParser = new \DOMDocument();
$DOMParser->loadHTML($html);
$xpath = new \DOMXPath($DOMParser);

$classname="c-explain2";
$getAllTable = $xpath->query("//dl[contains(@class, '$classname')]//");

foreach($getAllTable as $table){
            $allProperties = [];

            $table->getElementsByTagName('dt')[0]->nodeValue;

            $value = $table->getElementsByTagName('dd')[0]->nodeValue;
            $allProperties[] = [
                    'property' => $property, 
                    'value'=> $value];
            }
                $insertData[$start_id] = $allProperties;
                $MyTable = true; 

如何获得那些 dt 和 dd,然后要将它们放入数组中。有什么帮助吗?谢谢你。

标签: phpxpathweb-scrapingdomparser

解决方案


你的 XPath 表达式有问题,应该是"//dl[@class='$classname']"

此外,您似乎从未$property在循环中分配。尝试这个:

<?php
$html = <<<END
<dl class="c-explain2">
        <dt>所在地</dt>
        <dd>大阪府大阪市 北区天満1丁目25番1(地番&lt;/dd>
</dl>
END;

$DOMParser = new \DOMDocument();
$DOMParser->loadHTML($html);
$xpath = new \DOMXPath($DOMParser);

$classname   = "c-explain2";
$getAllTable = $xpath->query("//dl[@class='$classname']");

foreach ($getAllTable as $table)
{
    $allProperties = [];

    $property = $table->getElementsByTagName('dt')[0]->nodeValue;

    $value           = $table->getElementsByTagName('dd')[0]->nodeValue;
    $allProperties[] = [
        'property' => $property,
        'value' => $value
    ];
}

推荐阅读