2011-10-12 72 views
1

我有一段簡單的代碼,將來自谷歌發佈請求的數據流作爲PNG輸出。這是爲了使用谷歌創建一個QRcode。我想要做的是將此文件保存爲我的服務器上的PNG文件,我似乎無法弄清楚如何處理它,因爲我不熟悉使用流。下面的代碼:通過Google POST請求保存PNG

<?php 

    //This script will generate the slug ID and create a QRCode by requesting it from Google Chart API 
    header('content-type: image/png'); 

    $url = 'https://chart.googleapis.com/chart?'; 
    $chs = 'chs=150x150'; 
    $cht = 'cht=qr'; 
    $chl = 'chl='.urlencode('Hello World!'); 

    $qstring = $url ."&". $chs ."&". $cht ."&". $chl;  

    // Send the request, and print out the returned bytes. 
    $context = stream_context_create(
     array('http' => array(
      'method' => 'POST', 
      'content' => $qstring 
    ))); 
    fpassthru(fopen($url, 'r', false, $context)); 

?> 
+0

是否必須是帖子?生成的url作爲一個簡單的GET請求正常工作,這意味着您可以使用'echo file_get_contents(...)'代替。 –

+0

它可以是一個獲取請求,但仍然不確定我將如何保存它。 http://code.google.com/apis/chart/infographics/docs/overview.html – Throttlehead

+0

'file_put_contents('qr.png',file_get_contents(...));'fpassthru()用於直接發送輸出到客戶。對於你的代碼,你需要在之前打開的文件句柄上使用fwrite()。 –

回答

2

這是一種方式,根據您的代碼,並指定「這個保存爲我的服務器上的PNG文件」:

<?php 
$url = 'https://chart.googleapis.com/chart?'; 
$chs = 'chs=150x150'; 
$cht = 'cht=qr'; 
$chl = 'chl='.urlencode('Hello World!'); 

$qstring = $url ."&". $chs ."&". $cht ."&". $chl;  

$data = file_get_contents($qstring); 

$f = fopen('file.png', 'w'); 
fwrite($f, $data); 
fclose($f); 

添加錯誤檢查等調味。

+0

請讓我知道如何創建帶標識的二維碼 –

+0

嗨達人,它的工作很好。但是,如何添加此條形碼圖片的徽標中心?任何想法請分享 –

1

要將結果寫入文件,請使用fwrite()而不是fpassthru()。

您可以使用file_get_contents()和file_put_contents(),但是這些需要將整個圖像存儲在一個字符串中,這對於大圖像可能需要大量內存。這裏沒有問題,因爲qrcode圖像很小,但一般來說值得考慮。

您並不需要創建流上下文,因爲Web服務可以正常使用HTTP GET而不是POST。

還有一個名爲http_build_query()的函數,您可以使用它來簡化構建URL。

<?php 

$url = 'https://chart.googleapis.com/chart?' . http_build_query(array(
    'chs' => '150x150', 
    'cht' => 'qr', 
    'chl' => 'Hello World!' 
)); 

$src = fopen($url, 'rb'); 
$dst = fopen('file.png', 'w'); 
while (!feof($src)) { 
    fwrite($dst, fread($src, 1024)); 
} 

?>