如何使用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
相关产品推荐
相关产品推荐

