WordPress で外部サイトの RSS フィードをページ内に出力して表示するには

あるサイト内に別のサイトの RSS フィードをページ内に表示するにはウィジェットを使うと簡単です。 しかし、ページのコンテンツの一部として表示するには自由にタグ付けや情報を取り出して出力したい。 WordPress 2.8 以降には fetch_feed というキャッシュ機構を備えるフィード取得関数が用意されてます。 Function Reference/fetch feed « WordPress Codex ※使うには、feed.php をインクルードしておく必要がある。 これを使って ul, li のリストとしてはてなダイアリーの RSS を取得して書き出す処理を作ったので載せておきます。 fetch_feed は SimplePie を使って実装されているので、各フィードのエントリに関する項目は SimplePie Documentation: SimplePie_Item を参考にできます。 <?php include_once(ABSPATH . WPINC . '/feed.php'); $rss = fetch_feed('http://d.hatena.ne.jp/tilfin/rss2'); $rss_items = $rss->get_items(0, $rss->get\_item\_quantity(5) ); if ($rss_items) { foreach ( $rss_items as $item ) { $title = $item->get_title(); $pos = strpos($title, "\] "); if ($pos !== false) { $title = substr($title, $pos + 2); } echo '' . $item->get_date('Y.n.j') . ''; echo '' . $title; echo ''; } } ?> エントリーのタイトルから [タグ] は取り除くようにしています。自分は最後のタグとタイトルの間にスペースを1つ入れるルールにしているため上記のような簡略処理で書きました。

2010年3月18日 · Toshimitsu Takahashi

PHP フレームワークの人気動向を探ってみた

Google で最近のものに絞って検索をかけてみてヒット数を調べた。 調べたフレームワークは Symphony, CakePHP, Maple, Ethna, Zend Framework, Mojavi である。Smarty はテンプレートエンジンだがこれも調べてみた。 このうち、Maple, Ethna は国産フレームワークである。そのため日本語ページのみ対象にしてある。 一年以内 smarty php の検索結果のうち1年以内に更新された日本語 のページ 約 1,260,000 件 cakephp の検索結果のうち1年以内に更新された日本語 のページ 約 233,000 件 maple php の検索結果のうち1年以内に更新された日本語 のページ 約 196,000 件 symphony php の検索結果のうち1年以内に更新された日本語 のページ 約 115,000 件 zend framework php の検索結果のうち1年以内に更新された日本語 のページ 約 70,000 件 ethna php の検索結果のうち1年以内に更新された日本語 のページ 約 42,900 件 mojavi php の検索結果のうち1年以内に更新された日本語 のページ 約 9,660 件 3か月以内 maple php の検索結果のうち過去3か月に更新された日本語 のページ 約 86,200 件 cakephp の検索結果のうち過去3か月に更新された日本語 のページ 約 81,100 件 symphony php の検索結果のうち過去3か月に更新された日本語 のページ 約 54,200 件 smarty php の検索結果のうち過去3か月に更新された日本語 のページ 約 42,300 件 zend framework php の検索結果のうち過去3か月に更新された日本語 のページ 約 28,500 件 ethna php の検索結果のうち過去3か月に更新された日本語 のページ 約 12,000 件 mojavi php の検索結果のうち過去3か月に更新された日本語 のページ 約 3,590 件 ...

2008年11月19日 · Toshimitsu Takahashi

PHP での HTTP レスポンスを Transfer-Enconding: Chunked から Content-Length 指定に変えたい

レンタルサーバに制作した php のプログラムをアップしたら表示が遅い。ブラウザから見たときだけそうなり、wget すると一瞬で取得できるのです。 Firebugs で HTTPヘッダを見てみたら、Transfer-Encoding: chunked になってました。ということはそのレスポンスのストリーム終端が検出できずに Keep-Alive がタイムアウトするまで待ってしまってるのが原因のようです。それで php スクリプトの最後に flush(); とか書いてみたものの特に変化は見られずでした。 そもそもチャンクなのもどうのかなぁと思っていたら、 DoCoMo のiモードコンテンツ作成時の仕様 HTTPより http://www.nttdocomo.co.jp/service/imode/make/content/html/notice/basis/#p04 CGI作成時に「Content-Type」、「Content-Length」は必須項目となります。 とあるので、ケータイからアクセス対応も考えるとチャンクではなく Content-Length で対応しないと駄目ということです。 http://jp2.php.net/manual/ja/function.ob-get-length.php#13715 を見たところ、ズバリの答えがありました。 <? ob_start(); ?> 〜〜〜〜〜 <? $size=ob\_get\_length(); header("Content-Length: $size"); ob\_end\_flush(); ?> 世の中、php でケータイコンテンツ作られている事例は多々あると思うのですが、みなさんこのように実装されているのでしょうか。

2008年7月23日 · Toshimitsu Takahashi

PHP でのテンプレート機能に対応した簡単なメール送信クラスのサンプル

Smarty や Ethna などのアプリケーションフレームワークを使うレベルではないけど、ちょっとしたテンプレート対応させたメール送信を実装したいときのサンプル。 mb_send_mail を使っている。 sendmail.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 <?php mb\_internal\_encoding("UTF-8"); /** \* テンプレートに対応したメール送信クラス */ class SendMail { protected $content; protected $lang; protected $subject; protected $options; /** \* コンストラクタ \* @access public \* @param String $tplfile テンプレートファイルのパス \* @param String $lang メール送信時の言語指定 */ public function __construct($tplfile, $lang = "ja") { $this->content = file\_get\_contents($tplfile); $this->lang = $lang; } protected function replace_options($matches) { if (array\_key\_exists($matches\[1\], $this->options)) { return $this->options\[$matches\[1\]\]; } else { return ""; } } protected function extract_subject($matches) { $this->subject = trim($matches\[1\]); return ""; } /** \* テンプレートにマップの値をセットしてメールを指定された先に送信します。 \* @access public \* @param String $to メール送信先 \* @param Array $opts テンプレートに当てはまるマップ \* @return bool 送信結果 */ public function send($to, $opts) { $this->options = $opts; // テンプレートにマップの値をセット $content = preg\_replace\_callback('/\\{\\$(\[a-z0-9\]+)\\}/', array($this, "replace_options"), $this->content); // メールのヘッダとボディを切り分ける list($headers, $body) = preg_split("/\\n\\n/", $content, 2); // ヘッダから件名を抜き取る $headers = preg\_replace\_callback('/Subject\\:(.*)/', array($this, "extract_subject"), $headers); mb_language($this->lang); $result = mb\_send\_mail($to, $this->subject, $body, $headers); $this->options = NULL; $this->subject = NULL; return $result; } } ?> テンプレートファイルの例 (mail.tpl) send_mail() の仕様により、改行コードは LF である。ヘッダと本文の間は二回連続で改行する。 ...

2008年7月14日 · Toshimitsu Takahashi

MeCab + Senna + Tritonn で MySQL 全文検索を試す(2)

MeCab + Senna + Tritonn で MySQL 全文検索を試す - Tosshi Note の続き Google 風の検索 UI を実装してみた。 テーブルを作成 - SQL 1 2 3 4 5 6 7 8 9 CREATE TABLE fastsearch ( id INTEGER AUTO_INCREMENT, PRIMARY KEY (id), uri VARCHAR(512) NOT NULL, title VARCHAR(1024) NOT NULL, content MEDIUMTEXT, FULLTEXT INDEX USING NGRAM, SECTIONALIZE (title, content) ) DEFAULT CHARSET utf8 ENGINE = MyISAM; ※USING NGRAM をはずせば、MeCab の形態素解析になる。 ...

2007年12月5日 · Toshimitsu Takahashi

PHPでMySQLの標準機能で日本語を全文検索する(4)

検索部分の実装。markupで全文のうち最初にマッチする単語が出てくる部分を抜き出してハイライト化する。 ページ処理はしていない。検索時間は JavaScript で後から表示。 phpにあまり慣れていなかったものの、LAMP を改めて実感する手軽さだった。 find.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 <?php mb\_internal\_encoding("UTF-8"); mb\_regex\_encoding("UTF-8"); header('Content-Type:text/html;charset=utf-8'); require("db.php"); ?> <html> <head> <title>Full Text Search Result</title> <style type="text/css"> h1 { font-weight:normal; color:#2530e5; font-size:200%; font-family:'Arial'; margin-top:20px; } ol,li,p { margin:0; padding:0; } li { list-style:none; margin:1.75em 0; } a { font-weight:bold; } p { margin-top:0.25em; font-size:80%; line-height:1.5; width:530px; } em { font-weight:bold; font-style:normal; background-color:#ff0; } #hitcount { font-size:80%; border-top:#3366cc 1px solid; background-color:#e5ecf9; padding:3px; text-align:right; } </style> </head> <body> <h1>全文検索</h1> <form method="get" action="find.php"> <input type="text" name="find" value="<?php echo($_GET\['find'\]) ?>" style="width:300px"/> <input type="submit" value=" 検索 "/><br/> <input type="checkbox" id="titleonly" name="titleonly" value="1"/><label for="titleonly">タイトルのみ</label> </form> <?php function markup($content, $words) { $disp = ""; $ctnstart = mb_strpos($content, "\\n") + 1; $ret = $ctnstart; foreach ($words as $word){ $ret = mb_stripos($content, $word, $ret); if ($ret === false) { continue; } elseif ($ret < 30) { $ret = 0; } else { $disp = "..."; $ret -= 30; } if (mb_strlen($content) - $ctnstart <= 130) { $disp = mb_substr($content, $ctnstart); break; } $disp .= mb_substr($content, $ret, 130); if (mb_strlen($disp) >= 133) { $disp .= "..."; } break; } if (strlen($disp) == 0) { if (mb_strlen($content) - $ctnstart > 130) { return mb_substr($content, $ctnstart, 130)."..."; } else { return mb_substr($content, $ctnstart); } } $kk = array(); $kk\[\] = "#ffff00"; $kk\[\] = "#00ffff"; $kk\[\] = "#ff00ff"; $kk\[\] = "#00ff00"; $k = 0; foreach ($words as $word){ if (mb_eregi($word, $content, $wdarray)) { foreach ($wdarray as $soeji => $wd){ $disp = mbereg_replace($wd, "<em style=\\"background-color:".$kk\[$k\]."\\">".$wd."</em>", $disp); } } if (++$k == 4) { $k = 0; } } return $disp; } if ($_GET\['find'\]) { $starttime = (float)microtime(); ?> <div id="hitcount"></div> <ol> <?php $dbm = new DBManager("livedocs_ft"); if ($_GET\['titleonly'\] == 1) { $stmt = $dbm->findTitle($_GET\['find'\]); } else { $stmt = $dbm->find($_GET\['find'\]); } $hitcount = 0; if ($stmt->execute()) { while ($record = $stmt->fetch(PDO::FETCH_ASSOC)) { echo "<li><a href=\\"".$record\['uri'\]."\\">".$record\['title'\]."</a>\\n"; if ($_GET\['titleonly'\] == 1) { } else { echo "<p>"; echo markup($record\['content'\], $dbm->getMarkupWords()); echo "</p>"; } echo "<p>"; echo $record\['score'\]; echo "</p></li>"; $hitcount++; } } $endtime = (float)microtime(); ?> </ol> <?php } ?> <script type="text/javascript"><!-- document.getElementById('hitcount').innerHTML = '<?php echo "<b>".$_GET\['find'\]."</b> で検索した結果 <b>".$hitcount."</b> 件 (<b>"; printf("%.3f", ($endtime - $starttime)); echo "</b> 秒)"; ?>'; //--!> </script> </body> </html>

2007年4月29日 · Toshimitsu Takahashi

PHPでMySQLの標準機能で日本語を全文検索する(3)

htmlfiles は HTMLファイルのパスが書かれたテキストリストをコマンドラインでから流し込む。 $ php into.php < htmlfiles into.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 <?php mb\_internal\_encoding("UTF-8"); mb\_regex\_encoding("UTF-8"); require_once("db.php"); require_once("htmlindex.php"); class Register { var $dbm; var $uri; var $title; var $content; var $hie; public function Register() { $this->dbm = new DBManager("livedocs_ft"); $this->hie =new HtmlIndexExtractor(); } public function regist($htmlfile) { if (!$this->readFile($htmlfile)) { echo "\[ERR\] Can't open file. : $file\\n"; return; } $this->hie->extract($this->htmltext); if ($this->dbm->insertFullTextIndexPrimary($htmlfile, $this->hie->getTitle(), $this->hie->getContent())) { echo "\[OK\] Inserted into file : $htmlfile.\\n"; } else { echo "\[NG\] Inserted into file : $htmlfile.\\n"; } } private function readFile($file) { $fh = fopen($file, 'r'); if ($fh == FALSE) { return false; } $ctn = ""; while (! feof($fh)) { $ctn .= fgets($fh); } fclose($fh); $this->htmltext = $ctn; return true; } } $rg = new Register(); $stdin = fopen('php://stdin', 'r'); if ($stdin == FALSE) { echo "No STDIN\\n"; exit; } while (!feof($stdin)) { $idxfile = rtrim(fgets($stdin), "\\n"); $idxfile = trim($idxfile); if (strlen($idxfile) > 0) $rg->regist($idxfile); } fclose($stdin); echo "Registing Completed.\\n"; ?>

2007年4月28日 · Toshimitsu Takahashi

PHPでMySQLの標準機能で日本語を全文検索する(2)

PHPからMySQLへの接続にはPDOを使うことにした。テーブルは、単純にURI, タイトルとコンテントをフィールドとして用意、全文用のフィールドを分けたのは、ngram_prim の内容は ngram_sub にも入り重みが増すようにしてみた(一応、効いてると思われる)。Boolean Mode を使うとスコアは利用できないのでその対策は後述。 テーブル ft 1 2 3 4 5 6 7 8 9 10 11 CREATE TABLE ft ( id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, uri VARCHAR(255) NULL, title VARCHAR(512) NULL, content MEDIUMTEXT NULL, ngram_prim MEDIUMTEXT NULL, ngram_sub MEDIUMTEXT NULL, PRIMARY KEY(id), FULLTEXT INDEX ft_ftindex(ngram_prim, ngram_sub), INDEX ft_uri_index(uri) ); MySQL接続の設定を別ファイルに切り出す。 ...

2007年4月27日 · Toshimitsu Takahashi

PHP HTMLからタイトルとbodyのテキストを抽出

FullTextの登録用にHTMLからタイトルとbodyのテキスト抜き出す。XML_HTMLSax でパースして前述のテキストを抜き出すクラス HtmlIndexExtractor を作成した。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 <?php require_once('XML/XML_HTMLSax.php'); interface IndexExtractor { function extract($target); } class HtmlIndexExtractor implements IndexExtractor { private $parser; private $handler; private $title; private $content; private $str; private $getstr; public function HtmlIndexExtractor() { $this->parser=& new XML_HTMLSax(); $this->parser->set_object($this); $this->parser->set_option('XML\_OPTION\_TRIM\_DATA\_NODES'); $this->parser->set\_element\_handler('openHandler', 'closeHandler'); $this->parser->set\_data\_handler('dataHandler'); } public function extract($target) { /* $orgenc = mb\_detect\_encoding($target); if ($orgenc != "UTF-8") { $target = mb\_convert\_encoding($target, "UTF-8", $orgenc); } */ $this->parser->parse($target); } public function getTitle() { return $this->title; } public function getContent() { return $this->content; } function openHandler(& $parser,$name,$attrs) { $tagname = strtolower($name); if ($tagname == 'title' || $tagname == 'body') { $this->str = ""; $this->getstr = true; } } function closeHandler(& $parser,$name) { $tagname = strtolower($name); if ($tagname == 'title') { $this->title = $this->str; $this->getstr = false; } elseif ($tagname == 'body') { $this->content = $this->str; $this->getstr = false; } } function dataHandler(& $parser, $data) { if ($this->getstr) { $this->str .= htmlspecialchars_decode($data); } } function escapeHandler(& $parser,$data) {} function piHandler(& $parser,$target,$data) {} function jaspHandler(& $parser,$data) {} } ?>

2007年4月26日 · Toshimitsu Takahashi

MySQLの標準機能で日本語を全文検索する(1)

MySQL には全文検索機能が付いている。だが、ラテン語のようにスペースがないと語句の区切りを認識しないため、そのままでは日本語が検索できない。 MySQLで全文検索 - FULLTEXTインデックスの基礎知識|blog|たたみラボ を参考に構築してみた。 データベースの文字コードは UTF-8 で、最低検索語の指定は1が本当はよいとは思うが少しでも節約したいので、2とした。 my.cnf [mysqld] ft_min_word_len=2 まず必要なのは、日本語の語句分解なのだが、形態素解析ではなく N-gram により分解する。但し、日本語(ひらがな、カタカナ、漢字)、英語(アルファベット、数字)への分解をまずすることで無駄なインデックス作成を抑制するようにしてみた。日本語に関しては N-gram を用いて、英語に関しては、キャメル記法に対しては、分解するようにした。 myindex.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 <?php mb\_internal\_encoding("UTF-8"); mb\_regex\_encoding("UTF-8"); class FullTextSearcher { var $markwords; var $scorequery; public function FullTextSearcher() { } public function search_sql($statement) { return "'". $this->to_ngram($statement, 2) ."' IN BOOLEAN MODE"; } public function getScore() { return "'".$this->scorequery."'"; } public function getMarkupWords() { return $this->markwords; } private function to_ngram($string, $n){ $string = mb\_ereg\_replace("^(\\s| )+","", $string); $string = mb\_ereg\_replace("(\\s| )+$","", $string); $str_array = preg_split("/(\\s| )+/", $string); $result = array(); $markwords = array(); $scores = array(); foreach ($str_array as $str){ if ('-' != substr($str, 0, 1)) { $markwords\[\] = $str; } $r = $this->to\_ngram\_query($str, $n); $result\[\] = $r\[0\]; $scores\[\] = $r\[1\]; } $this->markwords = $markwords; $this->scorequery = join(' ', $scores); return join(' ', $result); } private function to\_ngram\_query($string, $n){ $string = trim($string); if ($string == ''){ return ''; } if ('-' != substr($string, 0, 1)) { $plus = true; } else { $plus = false; $string = substr($string, 1); } $length = mb_strlen($string); if ($length < $n){ if ($plus) { return array("+".$string."*", $string); } else { return array("-".$string."*", ""); } } $ngrams = array(); $scores = array(); $wa = new WordsAnalyzer(); $wa->loadStr($string); $wds = $wa->get_indexes(); foreach ($wds as $ngram){ if ($plus) { $ngrams\[\] = "+" . $ngram; $scores\[\] = $ngram; } else { $ngrams\[\] = "-" . $ngram; } } return array(join(' ', $ngrams), join(' ', $scores)); } } class WordsAnalyzer { private $words; public function WordsAnalyzer() { } public function get_indexes() { return array_keys($this->words); } public function get_fulltext() { return join(' ', array_keys($this->words)); } public function loadStr($str) { $this->words = array(); ereg_replace(13, "", $str); ereg_replace(10, " ", $str); $this->analyze_token($this->split_token($str)); } private function split_token($str) { $token = array(); while (1) { $bytes = mb_ereg("\[一-龠\]+|\[ぁ-ん\]+|\[ァ-ヴー\]+|\[a-zA-Z0-9\]+|\[a-zA-Z0-9\]+", $str, $match); if ($bytes == FALSE) break; $match = $match\[0\]; array_push($token, $match); $pos = strpos($str, $match); $str = substr($str, $pos+$bytes); } return $token; } private function analyze_token($token) { for ($i = 0, $len = count($token); $i < $len; $i++) { $word = $token\[$i\]; if (mb_ereg("\[一-龠\]", $word, $match) != FALSE) { if (mb_strlen($word) > 1) { $this->japanese($word); } else { $this->addword($word); } } else if (mb_ereg("\[ぁ-ん\]", $word, $match) != FALSE) { if (mb_strlen($word) > 1) { $this->hiragana($word); } } else if (mb_ereg("\[ァ-ヴー\]", $word, $match) != FALSE) { if (mb_strlen($word) > 1) { $this->japanese($word); } } else if (mb_ereg("\[a-zA-Z0-9\]", $word, $match) != FALSE) { if (strlen($word) > 0) { // camel-gram $this->english($word); } } else if (mb_ereg("\[a-zA-Z0-9\]", $word, $match) != FALSE) { if (mb_strlen($word) > 0) { // camel-gram $word = mb\_convert\_kana($word, 'rn'); $this->english($word); } } else { $this->addword($word); } } } private function addword($word) { if (strlen($word) == 0) return; $this->words{$word} = true; } private function japanese($str) { // bi-gram $ret = $this->split_ngram($str, 2); foreach ($ret as $key => $value) { if (mb_strlen($value) > 1) { $this->addword($value); } } } private function hiragana($str) { // bi-gram $ret = $this->split_ngram($str, 2); foreach ($ret as $key => $value) { if (mb_strlen($value) > 1) { if (mb_ereg("っ.|を|です|ます|する|ある|いる|から", $value, $match) != FALSE) { } else { $this->addword($value); } } } } private function english($str) { $this->addword($str); // そのままも登録 // キャメル記法を分解して登録 while(1){ $r = ereg("(\[a-z\]|\[A-z\]|\[0-9\])\[a-z\]+", $str, $match); if ($r == FALSE) { break; } $match = $match\[0\]; $this->addword($match); $pos = strpos($str, $match); $str = substr($str, $pos + $r); } } private function split_ngram($string, $n){ $ngrams = array(); $string = trim($string); if ($string == '') return ''; for ($i = 0, $len = mb_strlen($string); $i < $len; $i++) { $ngrams\[\] = mb_substr($string, $i, $n); } return $ngrams; } } ?>

2007年4月25日 · Toshimitsu Takahashi