json_decode在包装器类中使用API​​不会产生输出

时间:2019-01-14 23:57:50

标签: php curl

我需要一个帮助来在运行该代码时显示一个JSON代码,但是得到一个空页面,但是我想获取一个json代码结果,但我没有得到,我只是想看看如何获​​取它

代码:-

<?php
class Api
{
    const API_URL = 'http://yoursite/api/v2'; // API URL/Replace reseller domain
    const API_TOKEN = ''; // Your API token

    public function order($data) { // add order
        $post = array_merge([
            'api_token' => self::API_TOKEN,
            'action' => 'add'
        ], $data);

        return json_decode($this->connect($post));
    }

    public function status($order_id) { // get order status
        return json_decode($this->connect([
            'api_token' => self::API_TOKEN,
            'action' => 'status',
            'order' => $order_id
        ]));
    }

    public function balance() { // get balance
        return json_decode($this->connect([
            'api_token' => self::API_TOKEN,
            'action' => 'balance',
        ]));
    }

   public function packages() { // get packages list
        return json_decode($this->connect([
            'api_token' => self::API_TOKEN,
            'action' => 'packages',
        ]));
    }

    private function connect($post) {
        $_post = Array();
        foreach ($post as $name => $value) {
            $_post[$name] = urlencode($value);
        }

        $ch = curl_init(self::API_URL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));

        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        $result = curl_exec($ch);
        if (curl_errno($ch) != 0 && empty($result)) {
            $result = false;
        }
        curl_close($ch);
        return $result;
    }
}

// Examples

$api = new Api();

// Fetch Packages
$packages = $api->packages();

// Check balance
$balance = $api->balance();

// Add order
$order = $api->order(array('package' => 1, 'link' => 'http://example/link', 'quantity' => 100));

// Add Custom comments order
$order = $api->order(array('package' => 11, 'link' => 'http://example/link', 'quantity' => 4, 'comments' => "good pic\ngreat photo\n:)\n;)")); # Custom Comments

// Check Order status
$status = $api->status($order->order);

在此代码中只是获得一个空白页,但我想输出 公共职能平衡() 我想输出JSON响应只是帮助mep 我

如何输出json_decode? 请帮助我

1 个答案:

答案 0 :(得分:0)

正如评论所说,您需要输出一个变量。

print_r($order);
print_r($status);

我正在使用print_r,因为它可以很好地显示Array值。您最有可能从json_decode中获取哪种信息。

附带说明:当前使用json_decode的方式必须引用

之类的变量
$order->id

但是如果要以数组形式访问它们

$order['id'] 

然后您需要像这样使用json_decode

json_decode($json, true); // The True value is important

PHP docs json_decode