簡體   English   中英

如何正確格式化此字符串以在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);

我收到以下警告:

警告(2):file_get_contents( https://quickchart.io/chart?c= {type:'donut',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格式的問題,我需要做些什么來解決這個問題?

讓我們在這里打開file_get_contents()的文檔

注意:

如果要打開包含特殊字符(如空格)的URI,則需要使用urlencode()對URI進行編碼。

您應該使用urlencode或更好的http_build_query對查詢參數進行urlencode

例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM