LoginSignup
5
5

More than 5 years have passed since last update.

wordPress REST-APIのjson出力をphpで行う

Last updated at Posted at 2018-03-18

JSONデータをphpで扱う

wordPress REST-APIで吐き出されたJSONデータをphpで出力します。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>phpでjson</title>
</head>
<body>


<?php
$url = "http://example.net/wp-json/wp/v2/news/?_embed&per_page=7";
$json = file_get_contents($url);
$json = mb_convert_encoding($json, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');
$arr = json_decode($json,true);

if ($arr === NULL) {
        return;
}else{
        $json_count = count($arr);
        for($i=0;$i<$json_count;$i++){?>

            <h2>【ID番号】<?php echo $arr[$i]["id"];?></h2>
            <p>【ページタイトル】<?php echo $arr[$i]["title"]["rendered"];?></p>
            <p>【リンク】リンク先は<a href="<?php echo $arr[$i]["link"];?>">こちら</a></p>
            <?php $date = $arr[$i]["date"];?>
            <time>【日付】<?php echo date('Y年m月d日',  strtotime($date));?></time>
            <hr>
<?php
    }
}
?>

</body>
</html>

参考記事一覧

phpとjsonについて詳しくは下記の記事をご覧ください。
参考記事 PHPでJSONデータの取得の仕方

wordpressのREST-APIの使い方については前回私が書いた記事を参考にしてください。
参考記事 WordPress WP_REST_API 使い方の基本設定とエンドポイントの勉強

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