【问题标题】:Notice: Trying to get property of non-object CURL Result?注意:试图获取非对象 CURL 结果的属性?
【发布时间】:2018-08-26 23:21:03
【问题描述】:

您好,我正在尝试使用 API。 但是我不断收到这个奇怪的错误,我已经搜索了互联网,但在尝试阅读该错误时似乎无法修复它。

我收到此错误:注意:尝试在第 22 行的 C:\xampp\htdocs\index.php 中获取非对象的属性

这里是 index.php 的第 17 到 28 行

$server = "localhost:8087";
$player = $_SESSION['username'];
$password = $_SESSION['password'];
$params = array("Command" => "AccountsPassword", "Player" => $player, ":", "PW" => $password);
$api = Poker_API($params);
if ($api -> Result != "Ok") die($api -> Error . "<br/>" . "Go to the homepage to try again.");
if ($api -> Verified != "Yes") die("Password is incorrect. Go to the homepage to try again.");
$params = array("Command" => "AccountsSessionKey", "Player" => $player);
$api = Poker_API($params);
if ($api -> Result != "Ok") die($api -> Error . "<br/>" . "Go to the homepage to try again.");
$key = $api -> SessionKey;
$src = $server . "/?LoginName=" . $player . "&amp;SessionKey=" . $key;

这里是 api.php

<?php
  $url = "localhost:8087/api";              // Put your API path here
  $pw = "Removed";                  // put your API password here

  function Poker_API($params)
  {
    global $url, $pw;
    $params['Password'] = $pw;
    $params['JSON'] = 'Yes';
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($curl, CURLOPT_VERBOSE, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($curl);
    if (curl_errno($curl)) $obj = (object) array('Result' => 'Error', 'Error' => curl_error($curl)); 
    else if (empty($response)) $obj = (object) array('Result' => 'Error', 'Error' => 'Connection failed'); 
    else $obj = json_decode($response, true);
    curl_close($curl);
    print_r($response);
    //echo implode($params);
    return $obj;
    }

?>

【问题讨论】:

  • this $obj = json_decode($response, true); 返回关联的数组而不是对象。抛弃true,你会收到一个对象(除非有json错误)
  • 天哪,谢谢它有效!

标签: php arrays json object curl


【解决方案1】:

注意不是错误。 当您没有错误时,这可能会发生,因为您在此行中返回数组:

else $obj = json_decode($response, true);

True,作为第二个参数,强制此函数返回关联数组。所以,你没有对象可以调用。

【讨论】:

  • 如果是格式错误的 json?
  • @Cemal 然后json_decode() 返回null。错误可以在json_last_error_msg()中找到
  • 然后他会得到null作为返回值。这就是我写“可能”的原因。当然应该处理得更好。
  • 确实应该是这样,但是如果您在这里写答案,恕我直言,您实际上应该解决问题。这种简短的更正应该放在 cmets 部分,除非它作为一个整体呈现。
  • @Cemal 是的,你是绝对正确的。但是我的声誉低于 50,所以我无法评论主帖。
【解决方案2】:

尝试添加以下 2 行:

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

它对我有用。

【讨论】:

  • 为什么要这样做?你能解释一下这些行的作用吗?
猜你喜欢
  • 2018-11-22
  • 1970-01-01
  • 2013-03-05
  • 2018-09-11
相关资源
最近更新 更多