在 Linux 常使用到 pipe(|), 要如何讓 PHP 讀取 pipe 送過來的值呢?
- ex: cat file.txt | ./read_pipe.php # 將 file.txt cat 印出, 送給 read_pipe.php 接收處理.
主要是使用 php://stdin
接收, 詳細可見: PHP input/output streams, PHP I/O streams
將接收到的資料, 全部印出
<?php
$fp = fopen('php://stdin','r');
print stream_get_contents($fp);
?>
將接收到的資料, 全部印出
<?php
while ($line = trim(fgets(STDIN))) {
echo $line . "\n";
}
?>
將接收到的資料, 依 \n 分段印出
<?php
$fp = fopen('php://stdin','r');
while ($line = stream_get_line($fp, 65535, "\n")) {
echo $line . "\n";
}
?>