how to correctly format this string for use in a URL

558 Views Asked by At

I'm trying to create an image of a chart I'm using so that I can embed it into a pdf. I'm using chart.js to create the chart - although I'm using https://quickchart.io/ to create the chart by passing the chart information to the quickchart url.

I'm then trying to add it to a pdf by using tcpdf.

The string which I create from some arrays is:

$genderGraph = "https://quickchart.io/chart?c={type: 'doughnut',data:{labels:" . json_encode($genderchartjs['label']) . ", datasets: [{data:" . json_encode($genderchartjs['data']) . ",backgroundColor:" . json_encode($chartcolors) . "}]}}";

And if I echo what $genderGraph is following the above its:

https://quickchart.io/chart?c={type: 'doughnut',data:{labels:["Male","Female","Unknown"], datasets: [{data:[16,34,17],backgroundColor:["rgba(255, 99, 132, 1)","rgba(54, 162, 235, 1)","rgba(255, 206, 86, 1)","rgba(75, 192, 192, 1)","rgba(153, 102, 255, 1)","rgba(255, 159, 64, 1)","rgba(0, 0, 0, 1)"]}]}}

Which if you stick in a browser address bar will show you the correct image of the chart, exactly as I want it.

The problem is when I try to add the image to the pdf using file_get_contents()

$img = file_get_contents($genderGraph);
$pdf->Image('@' . $img);

I get the following warning:

Warning (2): file_get_contents(https://quickchart.io/chart?c={type: 'doughnut',data:{labels:["Male","Female","Unknown"], datasets: [{data:[16,34,17],backgroundColor:["rgba(255, 99, 132, 1)","rgba(54, 162, 235, 1)","rgba(255, 206, 86, 1)","rgba(75, 192, 192, 1)","rgba(153, 102, 255, 1)","rgba(255, 159, 64, 1)","rgba(0, 0, 0, 1)"]}]}}): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request

It appears to be a problem with the formatting of the URL, what do I need to do to fix this?

1

There are 1 best solutions below

0
Nik On BEST ANSWER

Lets open the doc for file_get_contents() here

Note:

If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().

You should encode your query parameter using urlencode or better http_build_query

Example:

<?php
$url = 'https://quickchart.io/chart';

// replace with your string
$c = "{type: 'doughnut',data:{labels:[\"Male\",\"Female\",\"Unknown\"], datasets: [{data:[16,34,17],backgroundColor:[\"rgba(255, 99, 132, 1)\",\"rgba(54, 162, 235, 1)\",\"rgba(255, 206, 86, 1)\",\"rgba(75, 192, 192, 1)\",\"rgba(153, 102, 255, 1)\",\"rgba(255, 159, 64, 1)\",\"rgba(0, 0, 0, 1)\"]}]}}";

$url = $url . '?' . http_build_query([
    'c' => $c
]);

$image = file_get_contents($url);
// pdf