如何正确格式化此字符串以便在 URL 中使用

how to correctly format this string for use in a URL

我正在尝试创建我正在使用的图表的图像,以便我可以将其嵌入到 pdf 中。我正在使用 chart.js 创建图表 - 虽然我正在使用 https://quickchart.io/ 通过将图表信息传递给 quickchart url.

创建图表

然后我尝试使用 tcpdf.

将其添加到 pdf 中

我从一些数组创建的字符串是:

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

如果我回显 $genderGraph 上面的内容:

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)"]}]}}

如果你坚持浏览器地址栏,它会显示正确的图表图像,完全符合我的要求。

问题是当我尝试使用 file_get_contents()

将图像添加到 pdf 时
$img = file_get_contents($genderGraph);
$pdf->Image('@' . $img);

我收到以下警告:

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

URL 的格式似乎有问题,我需要做什么来解决这个问题?

让我们打开 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().

您应该使用 urlencode 或更好的 http_build_query

对您的查询参数进行编码

示例:

<?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