LoginSignup
5
2

More than 5 years have passed since last update.

kintoneに添付した画像ファイルを PHPで表示する

Last updated at Posted at 2017-02-10

kintoneのデータに添付した画像ファイルを、PHPで表示します。

kintone接続のキホン

PHPから kintoneに接続するサンプルは、こちらのサイトなどが参考になります。

次のようなプログラムを作成します。

<?php
define("API_TOKEN", "");
define("SUB_DOMAIN", "");
define("APP_NO", "");

//サーバ送信するHTTPヘッダを設定
$context = stream_context_create(array (
        'http'=>array(
        'method'=>'GET',
        'header'=> "X-Cybozu-API-Token:". API_TOKEN ."\r\n"
    )
));

$id = 1; // 取得したいレコード番号

$param = 'app=' . APP_NO . '&id=' . $id;
$contents = file_get_contents('https://' . SUB_DOMAIN . '.cybozu.com/k/v1/record.json?' . $param, FALSE, $context);

// 正常に動作しない場合は、以下のコメントを外してください
//var_dump($http_response_header);

$data = json_decode($contents, true);
$data = $data['records'];

fileKeyを取得する

ファイルを取得するには、添付ファイルのフィールドの中の「fileKey」が必要です。

$data['添付ファイル']['value'][0]['fileKey'];

ファイルを取得する

続いて、ファイルを取得します。file.jsonfileKeyを渡して取得します。

$param = 'fileKey=' . $data['添付ファイル']['value'][0]['fileKey'];
$contents = file_get_contents('https://' . SUB_DOMAIN . '.cybozu.com/k/v1/file.json?' . $param, false, $context);

すると、「$contents」にファイルの内容がそのまま入ります。これを、<img>タグで表示させたいのですが、ここでは Base64にエンコードしてsrc属性にそのまま入れ込みます。

<img src="data:image/jpeg;base64,<?= base64_encode($contents);">

これで、画像が表示されます。

5
2
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
5
2