php - 如何使用 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,然后要将它们放入数组中。有什么帮助吗?谢谢你。
解决方案
你的 XPath 表达式有问题,应该是"//dl[@class='$classname']"
此外,您似乎从未$property
在循环中分配。尝试这个:
<?php
$html = <<<END
<dl class="c-explain2">
<dt>所在地</dt>
<dd>大阪府大阪市 北区天満1丁目25番1(地番</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
];
}
推荐阅读
- powerbi - 如何在 PowerBI 中对总和大于 24 小时的多个持续时间值求和
- apache - 使用 Apache 配置在 JSESSIONID cookie 上设置 SameSite 属性
- typescript - 如何在打字稿3.0中将对象传递给突变
- c++ - 说“内在”只是对编译器的建议是否正确?
- go - 将指针传递给接口时函数抛出错误?
- reactjs - 在 createStackNavigators 中的抽屉路径中获取图标 initialRoute 嵌套在 createDrawerNavigator 中
- c# - 获取特定应用程序的屏幕截图(Android 模拟器)
- unity3d - Unity 中的 ThreeJS 着色器
- python - 使用 pybind11,如何将我的代码拆分为多个模块/文件?
- regex - 如何用一个正则表达式提取字符串?