ITの隊長のブログ

ITの隊長のブログです。Rubyを使って仕事しています。最近も色々やっているお(^ω^ = ^ω^)

php_mecabでできなかったので、自分で書くことにしました。

スポンサードリンク

http://www.flickr.com/photos/35336901@N00/73129683
photo by gochie*


aipacommander.hatenablog.jp


teratail.com




待ったけど解決しなかったお('・ω・)


というわけで、PHPで自作してみました。

<?php

// mecabのパス
$path = '/usr/local/bin/mecab';

// 標準入力を利用し、キーボードからの入力を受け付ける
$stdin = fopen('php://stdin', 'r');
$str   = fgets($stdin);
fclose($stdin);

// 関数が存在するか確認
if (!function_exists('stream_get_contents')) {
    function stream_get_contents($handle) {
        $contents = '';
        while (!feof($handle)) {
            $contents .= fread($handle, 8192);
        }
        return $contents;
    }
}

$descriptorspec = array(
      0 => array("pipe", "r"),
      1 => array("pipe", "w")
);

$result = "";
$process = proc_open($path, $descriptorspec, $pipes);
if (is_resource($process)) {
    fwrite($pipes[0], $str);
    fclose($pipes[0]);
    $result = stream_get_contents($pipes[1]);
    fclose($pipes[1]);
    proc_close($process);
}
echo $result;


しかし、これだとプロセスを生成しないといけないので、非効率なんだよね―(処理的に)


とりあえず、これで使います。