如何使用PHP获取指定URL返回的浮点数值并赋值给变量
错误原因分析
- 缺少HTTP请求逻辑:
parse_url是用于解析URL字符串本身结构的工具函数,不会主动发起网络请求获取目标URL的返回内容,你没有拿到接口返回的带单位的数值字符串,自然无法提取到目标值。 - 对
parse_url返回值的使用错误:parse_url('http://example.com/weight')返回的数组仅包含scheme、host、path这几个核心键,不存在weight键,访问$url_components['weight']得到的是null值,后续parse_str解析空值得到的$params为空数组,所以不会输出任何内容。
正确实现方案
首先需要发起HTTP请求获取接口返回的字符串,再从字符串中提取浮点数值即可,以下提供两种常用实现方式:
方式1:使用file_get_contents(需确认php.ini中allow_url_fopen配置为开启状态)
$url = 'http://example.com/weight'; // 发起GET请求获取响应内容 $response = file_get_contents($url); // 提取字符串中的浮点数值 preg_match('/\d+\.?\d*/', $response, $matches); $weight = isset($matches[0]) ? floatval($matches[0]) : 0; echo $weight;
方式2:使用cURL(兼容性更强,不依赖allow_url_fopen配置)
$url = 'http://example.com/weight'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $response = curl_exec($ch); curl_close($ch); preg_match('/\d+\.?\d*/', $response, $matches); $weight = isset($matches[0]) ? floatval($matches[0]) : 0; echo $weight;
内容的提问来源于stack exchange,提问作者Raul Chiarella
相关产品推荐
相关产品推荐

