PHP报错:尝试获取非对象属性——URL动态变量调用问题
解决"Notice: Trying to get property of non-object"错误
看起来你遇到的问题根源在于动态生成的关键词没有做URL编码,再加上请求配置的小问题,导致Bing API返回了非预期的响应,进而触发了那个错误。咱们一步步来解决:
1. 先修复URL编码问题
你动态生成的$prNameUrl里包含空格,直接拼到URL里会破坏请求格式——HTTP URL里的空格必须转成%20或者用+替代。硬编码CATS的时候没有空格,所以请求正常,换成带空格的变量就不行了。
解决方法是用urlencode()对关键词进行编码:
$prNameUrl = $v->product_name.' '.$v->product_category.' '.$v->product_format; // 对关键词做URL编码,处理空格等特殊字符 $encodedPrName = urlencode($prNameUrl); $prNameUrlTwo = 'https://api.cognitive.microsoft.com/bing/v7.0/images/search?q='.$encodedPrName.'&count=4&mkt=en-US';
2. 修正请求头的Content-Type
你当前设置的Content-Type: multipart/form-data是错误的——这是用于上传文件的请求头,而Bing图片搜索是GET请求,根本不需要这个类型,甚至可以不设置。错误的请求头可能会被API拒绝,导致返回错误内容。
把请求头改成:
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Ocp-Apim-Subscription-Key: xxxxxxxxx' )); // 或者如果一定要设置Content-Type,用application/json也可以 // 'Content-Type: application/json',
3. 增加错误排查逻辑(避免后续踩坑)
为了能快速定位问题,建议在代码里增加curl请求和JSON解析的错误检查,这样下次出问题时你能立刻知道是哪一步错了:
修改后的完整代码示例:
$prNameUrl = $v->product_name.' '.$v->product_category.' '.$v->product_format; $encodedPrName = urlencode($prNameUrl); $sURL = 'https://api.cognitive.microsoft.com/bing/v7.0/images/search?q='.$encodedPrName.'&count=4&mkt=en-US'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $sURL); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Ocp-Apim-Subscription-Key: xxxxxxxxx' )); $contents = curl_exec($ch); // 检查curl请求是否失败 if($contents === false) { echo 'CURL请求出错: ' . curl_error($ch); curl_close($ch); exit; } curl_close($ch); $myContents = json_decode($contents); // 检查JSON是否解析成功 if($myContents === null) { echo 'JSON解析失败,API返回内容: ' . htmlspecialchars($contents); exit; } // 安全检查:确保value属性存在且是数组 if(isset($myContents->value) && is_array($myContents->value) && count($myContents->value) > 0) { foreach ($myContents->value as $imageContent) { // 额外检查属性是否存在,避免报错 if(isset($imageContent->webSearchUrl, $imageContent->thumbnailUrl)) { echo "<a href='{$imageContent->webSearchUrl}'><img src='{$imageContent->thumbnailUrl}' width='290' height='200' /></a>"; } } } else { // 如果API返回错误,显示错误信息 $errorMsg = isset($myContents->error->message) ? $myContents->error->message : '未找到图片或未知错误'; echo '请求结果异常: ' . $errorMsg; }
最后再确认两个点
- 确保你的API密钥
xxxxxxxxx是有效的,并且还有剩余的调用额度 - 确认
$v对象确实存在product_name、product_category、product_format这几个属性,避免生成的关键词为空
内容的提问来源于stack exchange,提问作者Swift123
相关产品推荐
相关产品推荐

