wp_remote_get请求动态URL接口,如何解析响应渲染为HTML展示
现有代码存在的问题
- 变量名不匹配:前面将请求结果赋值给
$request,后续解码JSON时却用了从未定义的$response变量,会直接触发PHP未定义变量报错 - 请求URL格式错误:
$url开头多了一个空格,会导致wp_remote_get发起无效请求,无法拿到正确响应 - 多余的原始响应输出:代码里直接
echo $body会把原始JSON字符串直接渲染到页面上,破坏前端展示效果 - 响应校验不完整:仅通过
is_wp_error判断请求失败无法捕获4xx、5xx类的服务端返回错误(比如接口限流、路径失效) - 缺少JSON解码校验:如果接口返回非JSON格式内容(比如HTML错误页),直接按数组取字段会触发语法错误
可直接运行的修正代码
// 清理URL前后多余空格,补充请求超时设置避免卡死 $url = 'https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139'; $request = wp_remote_get( $url, [ 'timeout' => 10, ] ); // 处理WP层面的请求错误(比如网络不通、DNS解析失败) if ( is_wp_error( $request ) ) { echo '<p>天气数据获取失败,请稍后再试</p>'; return; } // 校验服务端返回的HTTP状态码,仅200为正常响应 $response_code = wp_remote_retrieve_response_code( $request ); if ( 200 !== $response_code ) { echo '<p>接口请求异常,错误码:' . esc_html( $response_code ) . '</p>'; return; } // 解码JSON响应为关联数组 $api_response = json_decode( wp_remote_retrieve_body( $request ), true ); // 校验JSON解码是否成功 if ( JSON_ERROR_NONE !== json_last_error() ) { echo '<p>接口返回数据格式错误,无法解析</p>'; return; } // 以下为HTML渲染部分,可按需调整样式 ?> <div class="weather-widget" style="max-width: 320px; padding: 24px; border: 1px solid #e5e7eb; border-radius: 12px;"> <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;"> <img src="<?php echo esc_url( $api_response['weather'][0]['icon'] ); ?>" alt="<?php echo esc_attr( $api_response['weather'][0]['main'] ); ?>" style="width: 56px; height: 56px;" > <span style="font-size: 32px; font-weight: 600;"> <?php echo esc_html( $api_response['main']['temp'] . '℃' ); ?> </span> </div> <ul style="list-style: none; padding: 0; margin: 0; line-height: 2; color: #374151;"> <li>天气状况:<?php echo esc_html( $api_response['weather'][0]['description'] ); ?></li> <li>大气压力:<?php echo esc_html( $api_response['main']['pressure'] . ' hPa' ); ?></li> <li>相对湿度:<?php echo esc_html( $api_response['main']['humidity'] . '%' ); ?></li> <li>风速:<?php echo esc_html( $api_response['wind']['speed'] . ' m/s' ); ?></li> <li>3小时降水量:<?php echo esc_html( ( $api_response['rain']['3h'] ?? 0 ) . ' mm' ); ?></li> </ul> </div> <?php
实用优化建议
- 所有输出到前端的内容必须用WordPress提供的
esc_html、esc_url、esc_attr函数做转义,避免XSS安全风险 - 生产环境建议增加 transient 缓存机制,将接口请求结果缓存10-15分钟,既减少对第三方接口的请求压力,也能避免页面加载速度受第三方接口波动影响
- 如果需要适配不同用户位置的天气展示,可将URL中硬编码的
lat、lon参数替换为动态获取的经纬度值
内容的提问来源于stack exchange,提问作者Fay Kay
相关产品推荐
相关产品推荐

