You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PHP XPath查询提取HTML内容并生成指定结构的数组

你当前代码的问题是遍历逻辑直接将每一个li元素对应为结果数组的一个子项,没有按「日期+对应事件」的规则合并分组,调整遍历逻辑即可解决,以下是修复后的完整代码:

// 先修正XPath中拼写错误的类名,确保节点匹配准确
$tabledata = $xpath->query('//ol[contains(@class,"timeline-delivered")]/li[contains(@class, "timelineDate") or contains(@class, "Timeline-event")]');

$ShipmentDetail = [];
$currentGroup = null;

foreach ($tabledata as $node) {
    $class = $node->getAttribute('class');
    // 遇到日期节点就新建分组
    if (str_contains($class, 'timelineDate')) {
        $currentGroup = [trim($node->textContent)];
        $ShipmentDetail[] = &$currentGroup;
        continue;
    }
    // 遇到事件节点就把所有div内容追加到当前分组,这里使用了相对路径XPath查询当前节点下的div
    if (str_contains($class, 'Timeline-event') && $currentGroup !== null) {
        $divNodes = $xpath->query('./div', $node);
        foreach ($divNodes as $div) {
            $currentGroup[] = trim($div->textContent);
        }
    }
}
// 释放引用避免后续操作污染数组
unset($currentGroup);

echo '<pre>';
print_r($ShipmentDetail);

如果你的PHP版本低于8.0没有内置str_contains函数,可以替换成mb_strpos($class, '匹配的类名') !== false的写法实现相同判断逻辑,运行上述代码得到的数组结构和你期望的完全一致。

内容的提问来源于stack exchange,提问作者Muda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 16:39:03