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

使用phpQuery解析Steam页面时,如何获取body元素的class?

解决phpQuery解析Steam主页获取body主题class的问题

我在使用phpQuery解析Steam个人主页(https://steamcommunity.com/profiles/76561198870067621/)时遇到了一个问题——我需要获取body元素的class属性来实现背景渐变效果。但用echo($pq)输出时,body标签没有class;直接echo($file)输出时,body是带class的,可$file是字符串,没办法用$file->find("body")这种方式获取元素。请问怎么才能获取到body对象的class?我想要拿到SummerTheme、DefaultTheme这类主题类名。当前代码如下:

$ch = curl_init('https://steamcommunity.com/profiles/76561198870067621/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$file = curl_exec($ch);
curl_close($ch);
$pq = phpQuery::newDocument($file);

解决方案

  • 移除HTTP响应头干扰
    你开启了CURLOPT_HEADER选项,导致$file包含了HTTP响应头内容,phpQuery解析DOM时会因为这些非HTML内容出现异常,丢失body的class。把这个选项设为false,只获取纯HTML响应体:
$ch = curl_init('https://steamcommunity.com/profiles/76561198870067621/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false); // 关闭响应头获取
$file = curl_exec($ch);
curl_close($ch);
$pq = phpQuery::newDocument($file);
  • 指定HTML解析模式(可选)
    如果还是存在解析异常,改用newDocumentHTML方法明确指定HTML解析模式,提升兼容性:
$pq = phpQuery::newDocumentHTML($file);
  • 获取并提取主题类名
    通过phpQuery获取body的class属性,再用正则提取你需要的主题类名:
$bodyClass = $pq->find('body')->attr('class');
// 匹配SummerTheme或DefaultTheme,不存在则默认返回DefaultTheme
preg_match('/(SummerTheme|DefaultTheme)/', $bodyClass, $matches);
$targetClass = $matches[1] ?? 'DefaultTheme';
echo $targetClass;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 02:50:00