尝试使用Livezilla chatbot脚本与REST API进行通信时遇到麻烦,这两个我都存储在本地PC上。我正在使用与Livezilla chatbot API页面非常相似的代码片段,并且已经对其进行了修改,但是出现一些错误。
27.02.19 11:34:11 :: 1 ERR#129连接USER API时出错,响应无效: http://localhost/livezilla/programytalk.php(
注意:尝试获取非对象的属性“答案” 第11行的C:\ xampp \ htdocs \ livezilla \ programytalk.php )在第0行
programytalk.php的代码如下:
<?php
$requestobj = json_decode($_POST["livezilla_user_api_request"]);
$responseNode = array();
$responseNode["ResponseTo"] = "";
$responseNode["Id"] = rand(1111111,9999999);
$responseNode["SearchKB"] = false;
$url = "http://localhost:8989/api/rest/v1.0/ask? question=".rawurlencode($requestobj->Value)."&userid=".$requestobj-
>VisitorId;
$sdata = json_decode(file_get_contents($url));
$responseNode["Value"] = $sdata->answer;
if(!empty($responseNode["Value"]))
echo json_encode($responseNode);
?>
这是API响应的JSON格式:
[{"response":{"answer":"Good morning.","question":"hello world","userid":"1234567890"}},200]
答案 0 :(得分:2)
通过该API响应,您无需阅读
$responseNode["Value"] = $sdata->answer;
您无需阅读
$responseNode["Value"] = $sdata[0]->response->answer;
因为答案嵌套在响应下方...
提示:只要这样做
$data = json_decode('[{"response":{"answer":"Good morning.","question":"hello world","userid":"1234567890"}},200]');
print_r($data);
输出将是:
Array
(
[0] => stdClass Object
(
[response] => stdClass Object
(
[answer] => Good morning.
[question] => hello world
[userid] => 1234567890
)
)
[1] => 200
)
答案 1 :(得分:-3)
请执行此操作
<?php
$requestobj = json_decode($_POST["livezilla_user_api_request"]);
$responseNode = array();
$responseNode["ResponseTo"] = "";
$responseNode["Id"] = rand(1111111,9999999);
$responseNode["SearchKB"] = false;
$url = "http://localhost:8989/api/rest/v1.0/ask? question=".rawurlencode($requestobj->Value)."&userid=".$requestobj-
>VisitorId;
$sdata = json_decode(file_get_contents($url), true);
$responseNode["Value"] = $sdata->answer;
if(!empty($responseNode["Value"]))
echo json_encode($responseNode, true);
?>