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

如何用PHP获取HTML数据?请求完善tgju汇率站抓取代码

完善PHP获取汇率页面数据的代码

原代码仅能提取第一个nf类元素的内容,无法关联币种名称与对应价格。以下是完善后的代码,可批量获取所有币种的名称及对应汇率:

// 禁用libxml错误提示,适配网页不规范的HTML结构
libxml_use_internal_errors(true);

$url = "https://www.tgju.org/currency";
$content = file_get_contents($url);

if (!$content) {
    die("无法获取目标页面内容");
}

$dom = new DOMDocument();
$dom->loadHTML($content);
$finder = new DomXPath($dom);

// 定位所有包含币种数据的表格行
$rows = $finder->query("//tr[contains(@class, 'market-data-row')]");

$exchangeRates = [];

foreach ($rows as $row) {
    // 提取当前行的币种名称
    $nameNode = $finder->query(".//td[contains(@class, 'title')]/a", $row);
    // 提取当前行的币种价格(对应class为nf的元素)
    $priceNode = $finder->query(".//td[contains(@class, 'nf')]", $row);
    
    // 确保节点存在再提取数据,避免报错
    if ($nameNode->length > 0 && $priceNode->length > 0) {
        $currencyName = trim($nameNode->item(0)->nodeValue);
        $currencyPrice = trim($priceNode->item(0)->nodeValue);
        $exchangeRates[$currencyName] = $currencyPrice;
    }
}

// 输出所有币种汇率,可根据需求调整处理逻辑
print_r($exchangeRates);

// 恢复libxml默认错误提示
libxml_use_internal_errors(false);

代码说明

  • 错误处理:通过libxml_use_internal_errors(true)屏蔽网页HTML不规范导致的警告,保证DOM解析正常执行
  • 精准定位:通过market-data-row类定位每个币种所在的表格行,确保币种名称与价格一一对应
  • 安全提取:判断节点存在后再提取数据,避免空节点导致的运行错误
  • 灵活使用:最终结果存入关联数组,可直接根据币种名称(如'دلار آمریکا'即美元)获取对应价格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 00:37:26