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

PHP中如何通过XPath提取带关联链接的标题?

Hey there, the key issue here is that your original query pulls all titles at once, which makes it impossible to pair each title with its parent c-wrapper's link. Instead, we should iterate over each c-wrapper individually, then extract both the title and any associated link within that wrapper's context. Here's how to adjust your code:

Modified Code

$doc = new DOMDocument();
@$doc->loadHTML($result);
$xpath = new DOMXPath($doc);

// Get all c-wrapper elements first
$divs = $xpath->query("//div[contains(@class, 'c-wrapper')]");

foreach ($divs as $wrapper) {
    // Extract the title from the current wrapper
    $titleQuery = $xpath->query(".//div[contains(@class, 'c-link-data-title')]/h4", $wrapper);
    if ($titleQuery->length === 0) continue; // Skip if no title exists
    $titleText = $titleQuery->item(0)->textContent;
    
    // Check if the current wrapper has an <a> link (direct child, as per your HTML structure)
    $linkQuery = $xpath->query("./a", $wrapper);
    $linkExtracted = $linkQuery->length > 0 ? $linkQuery->item(0)->getAttribute('href') : '';
    
    // Output based on whether we found a link (added htmlspecialchars for safety)
    if (!empty($linkExtracted)) {
        echo "<a href='" . htmlspecialchars($linkExtracted) . "'>" . htmlspecialchars($titleText) . "</a><br>";
    } else {
        echo htmlspecialchars($titleText) . "<br>";
    }
}

Why This Works

  • We loop through each c-wrapper one by one, ensuring we handle each title and its potential link as a paired set.
  • Using the second parameter in $xpath->query() (the $wrapper element) restricts the search to only elements inside that specific wrapper—this is the critical detail that keeps the title and its parent's link connected.
  • We added htmlspecialchars() to safely escape the output, which prevents XSS issues if your titles or links contain special characters like quotes or angle brackets.

Note on Your Original Query

You don't need to modify your original $titles query—replacing it with this wrapper-focused approach solves the pairing problem entirely. This way, you never lose the connection between a title and whether its wrapper includes a link.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:28:38