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

如何用PHP从XML Sitemap URL提取链接?现有代码无法运行

XML Sitemap URL提取工具修复方案

你的代码无法正常提取内容,核心问题在于忽略XML命名空间、错误处理不完善,且缺少前端交互表单。以下是修复后的完整实现:

问题分析

  1. XML命名空间未处理:标准站点地图XML默认带有http://www.sitemaps.org/schemas/sitemap/0.9命名空间,直接用$xml->url无法遍历到目标节点。
  2. 错误信息不明确:原代码仅提示"Error loading XML",无法定位具体问题(如网络请求失败、XML格式错误)。
  3. 未支持压缩Sitemap:多数站点会提供gzip压缩的sitemap文件,simplexml_load_file无法直接解析这类文件。
  4. 缺少前端表单:原代码仅包含后端逻辑,没有用户输入URL的交互界面。

修复后的完整代码

<?php
function extractSitemapUrls($sitemapUrl) {
    $urls = [];
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $sitemapUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip'); // 支持gzip解压
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 跟随重定向
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 设置超时时间
    
    $xmlContent = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if (curl_errno($ch)) {
        return ['error' => '请求失败: ' . curl_error($ch)];
    }
    
    if ($httpCode !== 200) {
        return ['error' => 'HTTP错误: ' . $httpCode];
    }
    
    curl_close($ch);
    
    // 启用错误捕获
    libxml_use_internal_errors(true);
    $xml = simplexml_load_string($xmlContent);
    
    if ($xml === false) {
        $errors = [];
        foreach (libxml_get_errors() as $error) {
            $errors[] = $error->message;
        }
        libxml_clear_errors();
        return ['error' => 'XML解析错误: ' . implode(', ', $errors)];
    }
    
    // 处理站点地图命名空间
    $ns = $xml->getNamespaces(true);
    $sitemapNs = isset($ns['']) ? $ns[''] : 'http://www.sitemaps.org/schemas/sitemap/0.9';
    $children = $xml->children($sitemapNs);
    
    // 判断是普通sitemap还是sitemap索引
    if (isset($children->url)) {
        // 普通sitemap,提取loc节点
        foreach ($children->url as $url) {
            $urls[] = (string)$url->loc;
        }
    } elseif (isset($children->sitemap)) {
        // sitemap索引,递归提取子sitemap的URL
        foreach ($children->sitemap as $sitemap) {
            $childUrls = extractSitemapUrls((string)$sitemap->loc);
            if (isset($childUrls['error'])) {
                $urls[] = '子sitemap错误: ' . $childUrls['error'];
            } else {
                $urls = array_merge($urls, $childUrls);
            }
        }
    } else {
        return ['error' => '不支持的sitemap格式'];
    }
    
    return $urls;
}

$output = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sitemapUrl = trim($_POST['sitemap_url']);
    
    if (filter_var($sitemapUrl, FILTER_VALIDATE_URL)) {
        $urls = extractSitemapUrls($sitemapUrl);
        
        if (isset($urls['error'])) {
            $output = '<div style="color: red;">' . $urls['error'] . '</div>';
        } else {
            $output = '<h2>提取到的URL:</h2><ul>';
            foreach ($urls as $url) {
                $output .= '<li><a href="' . htmlspecialchars($url) . '" target="_blank">' . htmlspecialchars($url) . '</a></li>';
            }
            $output .= '</ul>';
        }
    } else {
        $output = '<div style="color: red;">请输入有效的URL地址</div>';
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>XML Sitemap URL提取工具</title>
    <style>
        body { max-width: 800px; margin: 20px auto; font-family: Arial, sans-serif; }
        .form-group { margin-bottom: 20px; }
        input[type="url"] { width: 100%; padding: 8px; box-sizing: border-box; }
        button { padding: 8px 16px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
        ul { list-style: none; padding-left: 0; }
        li { margin: 5px 0; padding: 5px; border-bottom: 1px solid #eee; }
    </style>
</head>
<body>
    <h1>XML Sitemap URL提取工具</h1>
    <form method="POST">
        <div class="form-group">
            <label for="sitemap_url">输入站点地图URL:</label>
            <input type="url" id="sitemap_url" name="sitemap_url" required placeholder="例如: https://example.com/sitemap.xml">
        </div>
        <button type="submit">提取URL</button>
    </form>
    
    <?php echo $output; ?>
</body>
</html>

修复说明

  1. CURL请求替代原生方法:支持gzip解压、重定向跟随和超时控制,同时捕获网络层面的错误信息。
  2. 命名空间解析:自动识别标准sitemap命名空间,确保能正确遍历目标节点。
  3. 支持索引型Sitemap:递归提取索引文件中的子sitemap链接,覆盖更多场景。
  4. 精细化错误反馈:展示网络请求、XML解析等环节的具体错误,方便排查问题。
  5. 完整前端界面:包含输入表单和基础样式,实现完整的用户交互流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:43:23