Saving PNG from Google POST request
I have a simple bit of code that outputs the stream from a google post request as a PNG. It's for using google to create a QRcode. What I want to do though is save this as a PNG file on my server and I can't seem to figure out how to go about it as I'm not so familiar with working with streams. Here's the code:
<?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));
开发者_如何学Python
?>
This is one way, based on your code and specified 'save this as a PNG file on my server':
<?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);
Add error checking etc. to taste.
To write the result to a file, use fwrite() instead of fpassthru().
You could use file_get_contents() and file_put_contents(), but these require storing the entire image in a string, which could be memory intensive for large images. It's not an issue here since the qrcode images are small, but it's worth thinking about in general.
You don't really need to create a stream context, since the web service will work fine with an HTTP GET instead of POST.
There is also a function called http_build_query() which you can use to simplify building the 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));
}
?>
精彩评论