非对象的PHP属性 - URL内的变量

时间:2018-01-03 13:49:47

标签: php api variables

我在尝试将动态变量应用到URL时遇到错误,它自身也被设置为变量$ sURL。
如果我更改了'。$ prNameUrl。'以关键字CATS为例,它工作正常。但是一旦我输入变量,我就会得到错误: 注意:尝试获取非对象的属性

$prNameUrl = $v->product_name.' '.$v->product_category.' '.$v->product_format;


$prNameUrlTwo = 'https://api.cognitive.microsoft.com/bing/v7.0/images/search?q='.$prNameUrl.'&count=4&mkt=en-US';

$sURL = $prNameUrlTwo;

$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(
    'Content-Type: multipart/form-data',
    'Ocp-Apim-Subscription-Key: xxxxxxxxx'
));
$contents = curl_exec($ch);
$myContents = json_decode($contents);
if(count($myContents->value) > 0) {
    foreach ($myContents->value as $imageContent) {

        echo "<a href='{$imageContent->webSearchUrl}'><img src='{$imageContent->thumbnailUrl}' width='290' height='200' /></a>";

    }
}

1 个答案:

答案 0 :(得分:0)

我用&#34; urlencode&#34;解决了这个问题。

$sURL = $WebSearchURL . urlencode( '\'' . $prNameUrl . '\'') . '&count=4&mkt=en-US';

完整的解决方案代码

$prNameUrl = $v->product_name.' '.$v->product_category.' '.$v->product_format;
echo $prNameUrl;
echo '<br>';
echo '<br>';

$prNameUrlTwo = 'https://api.cognitive.microsoft.com/bing/v7.0/images/search?q=';

$WebSearchURL = $prNameUrlTwo ;

$sURL = $WebSearchURL . urlencode( '\'' . $prNameUrl . '\'') . '&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(
    'Content-Type: multipart/form-data',
    'Ocp-Apim-Subscription-Key: xxxxxxxxxx'
));
$contents = curl_exec($ch);
$myContents = json_decode($contents);
if(count($myContents->value) > 0) {
    foreach ($myContents->value as $imageContent) {

        echo "<a href='{$imageContent->webSearchUrl}'><img src='{$imageContent->thumbnailUrl}' width='290' height='200' /></a>";

    }
}