6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP経由で別サイトからJSONを取得する

Last updated at Posted at 2018-07-26

はじめに

こちらの記事 を参考にGoogleスプレッドシートの内容をJSONで返却出来るようにしてからサーバー経由で取得してみる。

CORSで引っかかった場合とか、内容をキャッシュしたい時等にもこの方法が使えるはず。

スプレッドシートからのJSON取得

上記の記事を参考にすれば特に問題なく出来るはず。

DockerでAPIとなるサーバーを用意

docker run --name php -d -p 8080:80 -v '($pwd):/var/www/html' php:7.1-apache

PHPでAPIを用意

api.php
<?php
$url = '[GoogleスプレッドシートのURL]';

$curl = curl_init();
curl_setopt_array($curl,[
    CURLOPT_URL => $url,
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_RETURNTRANSFER => true,
]);

$result = curl_exec($curl);
// 必要に応じてこねくり回す
echo $result;

curl_close($curl);

ブラウザからアクセスして確認

http://localhost:8080/api.php
[ { "id": 1, "name": "いわし", "value": 100 }, { "id": 2, "name": "うし", "value": 200 }, { "id": 3, "name": "ぶた", "value": 300 }, { "id": 4, "name": "とり", "value": 400 } ]

axiosからアクセス

先日の記事 の index.js でのアクセス先を変更してアクセス

    mounted () {
        axios
            .get("api.php")
            .then(response => {this.results = response.data})
    }
05.png
6
1
0

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
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?