1
votes

I am using Google Charts from a URL for example:

http://chart.apis.google.com/chart?cht=lc&chs=250x100&chds=0,20...

How do I go about using PHP to save the image. I have tried:

$image = file_get_contents($lineChart->getUrl());
file_put_contents('playerchart.png', $image);

and

$ch = curl_init($lineChart->getUrl());
$fp = fopen('playerchart.png', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

However, both seem to corrupt the image and the image ends up not working.

Any ideas? Thanks

2
What does print_r($lineChart->getUrl()) show, also check your error logs, or rename the file to playerchart.png.txt and check it for php errors ect. - Lawrence Cherone

2 Answers

2
votes

I tested the following code and I got a proper PNG that I could open in Preview.

$image = file_get_contents('http://chart.apis.google.com/chart?cht=lc&chs=250x10
0&chds=0,20');
file_put_contents('playerchart.png', $image);

Given that the above works, I would say that there is fair chance that there is an issue with the $lineChart->getURL() and it might not be returning exactly what you expect. (I'd say print it out to the screen and double check, there might be some other characters or which space or the like in there. The 'image' that you are saving to disk might actually be the HTML for a 404 page!)

If you'd like an alternative way of saving the file, I would suggest the below. This will fail if the destination URL is not an image.

$im = imagecreatefrompng($theurl);
imagepng ($im, 'mypic.png');
imagedestroy($im);
0
votes

This works for me:

<?php
$img = file_get_contents("http://chart.apis.google.com/chart?cht=lc&chs=250x100&chds=0,20");
file_put_contents("test.png", $img);
?>