2012-07-22 87 views
0

我使用exec來抓取curl輸出(我需要使用curl作爲linux命令)。檢索exec()輸出時出錯

當我使用php_cli我看到一個捲曲的輸出開始我的文件:

% Total % Received % Xferd Average Speed Time Time  Time Current 
           Dload Upload Total Spent Left Speed 
100 75480 100 75480 0  0 55411  0 0:00:01 0:00:01 --:--:-- 60432 

這意味着所有的文件已正確下載(〜75 KB)。

我有這樣的代碼:

$page = exec('curl http://www.example.com/test.html'); 

我得到一個非常奇怪的輸出,我只得到:</html>

(這是我的的test.html文件的結尾)

我真的不明白原因,CURL似乎下載了所有文件,但是在$頁中我只能得到7個字符(最新的7個字符)。

爲什麼?

P.S.我知道我可以使用其他php函數下載源代碼,但我必須使用curl(作爲linux命令)。

+0

的可能重複[返回Perl的輸出到PHP(http://stackoverflow.com/questions/21407590/return- perl-output-to-php) – 2016-01-29 11:08:25

回答

3

除非這是一個非常奇怪的要求,爲什麼不使用PHP cURL庫呢?你可以更好地控制發生的情況,以及調用參數(超時等)。

如果你真的必須使用curl命令行二進制從PHP:

1) Use shell_exec() (this solves your problem) 
2) Use 2>&1 at end of command (you might need stderr output as well as stdout) 
3) Use the full path to curl utility: do not rely on PATH setting. 
+1

在PHP沒有curl支持的環境中,你可能有時候需要用curl來做些事情,所以有一個外部執行回退仍然很有用。 – nextgentech 2013-07-17 05:58:31

3

RTM for exec()

它返回

從命令結果的最後一行。

您必須將第二個參數設置爲exec(),該參數將包含所執行命令的所有輸出。

例子:

<?php 
$allOutputLines = array(); 
$returnCode = 0; 
$lastOutputLine = exec(
    'curl http://www.example.com/test.html', 
    $allOutputLines, 
    $returnCode 
); 

echo 'The command was executed and with return code: ' . $returnCode . "\n"; 
echo 'The last line outputted by the command was: ' . $lastOutputLine . "\n"; 
echo 'The full command output was: ' . "\n"; 
echo implode("\n", $allOutputLines) . "\n"; 

?>