首页 > 解决方案 > json_decode 在包装类中使用 API 不会产生输出

问题描述

我需要帮助以在此代码中显示 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);

在这段代码中我只是得到一个空白页但我想输出公共函数 balance () 我想输出 JSON 响应只是帮助我

如何输出它的 json_decode?请帮我

标签: phpcurl

解决方案


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

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 文档 json_decode


推荐阅读