LoginSignup
4
4

More than 5 years have passed since last update.

WebAPIを利用する際のクロスドメイン制約回避(JSON形式)

Last updated at Posted at 2015-10-24

概要

クロスドメイン制約を回避し、JSON形式で出力するPHPのサンプルコードです。
PHPを間に挟んで通信することで、クロスドメイン制約を回避することができます。

JSON形式で応答を返すWebAPIを利用しようと思ったところ、クロスドメイン通信に悩んだため今回投稿しました。

使用したAPIについて

今回はMarineTrafficAPIのID25番、Simplified JSON sample responsewoを使用しました。(有料)
http://www.marinetraffic.com/jp/ais-api-services/documentation/api-service:25

ソースコード

コードは以下の通りです。

ajax.php
<?php

try
{
    $API = null;
    $url = "http://services.marinetraffic.com/api/exportvessel/自分のAPIキー/timespan:20/mmsi:431000628/protocol:json";

    //ファイルの内容の読み込み
    $json = file_get_contents($url);

    //連想配列にする
    $users = json_decode($json,true);

    $API[] = array(
        'mmsi'=>$users[0][0],//二次元配列
        'time'=>$users[0][6]
    );

    //JSON形式で出力する
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode( $API, JSON_UNESCAPED_UNICODE );
    exit;

}
catch (PDOException $e)
{
    //例外処理
    die('Error:' . $e->getMessage());
}

実行結果

[{"mmsi":"xxxxxxxx","time":"2015-10-24T13:34:46"}]
と表示され、APIから情報を取得できたことが分かります。
(mmsiは伏せておきます。)

備考

自分はQiitaへの投稿が初めてなので、至らない点が多々あるかと思います(´・ω・`)

4
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4