1
0

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.

CakePHPではてブAPI

Last updated at Posted at 2017-01-09

はじめに

APIを初めて使ったというだけのメモ書きです。
file_get_contentsで取ればいいんだ、というだけです。

ほとんどSyncerさんのコードをパク……参考にしました
https://syncer.jp/hatebu-api-matome

CakePHPのバージョンは2.9.1です。

コード

Controller/HatebuController.php
<?php

App::uses('AppController', 'Controller');

class HatebuController extends AppController {

	public $uses = null; // Model使わない

	public function index() {

		// チェックするURL
		$target_url = $this->request->data('target_url');

		// JSONデータを取得
		$count = @file_get_contents( 
			'http://api.b.st-hatena.com/entry.count?url='
			. rawurlencode( $target_url )
		);

		// データが存在しない場合は0扱い
		if( !isset($count) || empty($count) ) {
			$count = 0;
		}
		
		// Viewに値を渡す
		$this->set(compact('target_url','count'));
	}
	
}
View/Hatebu/index.ctp

<h2>はてなブックマーク総数カウンター</h2>

<?php
	echo $this->Form->create(false,array(
		'type' => 'post',
	));
	echo $this->Form->input('target_url',array(
		'type' => 'url',
		'label' => 'URL (http://またはhttps://から入力)',
	));

	echo $this->Form->submit('Submit');
	echo $this->Form->end();
?>

<br><br>

<h3>URL : <?php echo $target_url; ?></h3>
<h3>結果は [ <?php echo $count ?> ] 件です</h3>

以上です

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?