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

时间:2019-03-30 19:52:44

标签: php url-encoding

我正在尝试创建正在使用的图表的图像,以便可以将其嵌入到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);

我收到以下警告:

  

警告(2):file_get_contents(https://quickchart.io/chart?c= {type:'doughnut',data:{labels:[“ Male”,“ Female”,“ Unknown”],数据集:[{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)“]} ]}}):无法打开流:HTTP请求失败! HTTP / 1.1 400错误请求

URL的格式似乎有问题,我该怎么做才能解决此问题?

1 个答案:

答案 0 :(得分:0)

让我们打开file_get_contents() here

的文档
  

注意:

     

如果要打开带有特殊字符(例如空格)的URI,则需要使用urlencode()对URI进行编码。

您应该使用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