当我试图通过cURL调用YQL时,我得到了以下错误。
不支持HTTP版本描述:web服务器"engine1.yql.vip.bf1.yahoo.com"正在使用不受支持的HTTP协议版本
以下是使用的代码
// URL
$URL = "https://query.yahooapis.com/v1/public/yql?q=select * from html where url="http://www.infibeam.com/Books/search?q=9788179917558" and xpath="//span[@class='infiPrice amount price']/text()"&format=json";
// set url
curl_setopt($ch, CURLOPT_URL, $URL);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
echo $output;
?>
从浏览器调用相同的URL效果良好
https://query.yahooapis.com/v1/public/yql?q=select*来自html,其中url="http://www.infibeam.com/Books/search?q=9788179917558"以及xpath="//span[@class='iniPrice amount price']/text()"&format=json
有人能告诉我代码里出了什么问题吗?
问题可能是因为您提供给cURL的url无效。您需要准备/编码查询字符串的各个值,以便在url中使用。
你可以使用urlencode()
:
$q = urlencode("select * from html where url="http://www.infibeam.com/Books/search?q=9788179917558" and xpath="//span[@class='infiPrice amount price']/text()"");
$URL = "https://query.yahooapis.com/v1/public/yql?q={$q}&format=json";
在这种情况下,我只对q
的值进行了编码,因为format
不包含不能在url中使用的字符,但通常情况下,您会对任何不知道或不控制的值进行编码。
好的,我明白了。。问题出在https上。使用以下代码段调试
if (false === ($data = curl_exec($ch))) {
die("Eek! Curl error! " . curl_error($ch));
}
添加了以下代码以默认接受SSL证书。
$options = array(CURLOPT_URL => $URL,
CURLOPT_HEADER => "Content-Type:text/xml",
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_RETURNTRANSFER => TRUE
);
完整的代码在这里
<?php
// create curl resource
$ch = curl_init();
// URL
$q = urlencode("select * from html where url="http://www.infibeam.com/Books/search?q=9788179917558" and xpath="//span[@class='infiPrice amount price']/text()"");
$URL = "https://query.yahooapis.com/v1/public/yql?q={$q}&format=json";
echo "URL is ".$URL;
$ch = curl_init();
//Define curl options in an array
$options = array(CURLOPT_URL => $URL,
CURLOPT_HEADER => "Content-Type:text/xml",
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_RETURNTRANSFER => TRUE
);
//Set options against curl object
curl_setopt_array($ch, $options);
//Assign execution of curl object to a variable
$data = curl_exec($ch);
echo($data);
//Pass results to the SimpleXMLElement function
//$xml = new SimpleXMLElement($data);
echo($data);
if (false === ($data = curl_exec($ch))) {
die("Eek! Curl error! " . curl_error($ch));
}
if (200 !== (int)curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
die("Oh dear, no 200 OK?!");
}
//Close curl object
curl_close($ch);
?>