PHP将Json api数据绑定到表

时间:2017-04-01 14:31:31

标签: php html json api data-binding

我正在连接到一个并不真正拥有大量文档的API:我想将返回的数据绑定到一个表中,但此刻它甚至都没有加载...我很擅长这个......我只是不确定如何实际绑定数据...谢谢!

来自文档的示例回复:

 {
    "service":"1",
    "name":"Custom Comments",
    "type":"Custom Comments"
  }

HTML

 <div class="col-sm-9">

    <?php    $api = new Api();   ?>

   <?php    $services = $api->services(); # return all services ?>
        </div><!-- col-sm-9 -->

API CLASS

<?php
   class Api
   {
      public $api_url = 'http://apiurl'; // API URL

      public $api_key = 'key'; // Your API key

      public function order($data) { // add order
        $post = array_merge(array('key' => $this->api_key, 'action' => 'add'), $data);
        return json_decode($this->connect($post));
      }

      public function status($order_id) { // get order status
        return json_decode($this->connect(array(
          'key' => $this->api_key,
          'action' => 'status',
          'id' => $order_id
        )));
      }

      public function services() { // get services
        return json_decode($this->connect(array(
          'key' => $this->api_key,
          'action' => 'services',
        )));
      }


      private function connect($post) {
        $_post = Array();
        if (is_array($post)) {
          foreach ($post as $name => $value) {
            $_post[] = $name.'='.urlencode($value);
          }
        }
        $ch = curl_init($this->api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if (is_array($post)) {
          curl_setopt($ch, CURLOPT_POSTFIELDS, join('&', $_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;
      }
   }

0 个答案:

没有答案