如何使用 php 转义要在 Highcharts 中显示的数据中的单引号?

我正在尝试显示一个包含工具提示的图表,该工具提示显示一个可以包含撇号(单引号)的字符串。使用 php 从数据库中检索数据。


我要显示的系列中每个点的数据由 x 值(日期时间)、y 值(数字)、距离和要在工具提示中显示的名称(字符串)组成。一切正常,直到从数据库读取的名称包含单引号,例如 Tegg's,此时图表不显示。我认为这是因为 JSON_ENCODE 不会转义单引号字符串中的单引号。我无法在 JSON_ENCODE 之前转义单引号,因为它会转义转义字符。我怎样才能让它工作?


我的代码如下:


foreach ($this->hcRides as $ride)

{

    $point['x'] = strtotime($ride->event_date) * 1000;

    $point['y'] = $ride->ranking_points;

    $point['name'] = "'$ride->event_name'";

    $point['distance'] = "'$ride->distance'";


    array_push($countingRideData, json_encode($point));

}


// Strip the double-quotes out of the JSON

$countingRideDataString = str_replace('"', "", join($countingRideData, ','));

然后我将 $countingRideDataString 回显为系列中的数据。


hcoptions.series.push({

                type: 'column',

                name: 'Counting Rides',

                data: [<?php echo $countingRideDataString; ?>],

                color: '#222845',

                tooltip: {

                    customTooltip: function() {

                        return '<table class="tt-chart-table"><thead><tr><th>' + this.key + '</th></tr></thead><tbody><tr><td>' + this.point.distance + '</td></tr><tr><td><b>' + this.y + '</b> points</td></tr></tbody></table>'

                    }

                },

                zIndex: 2

            });


守候你守候我
浏览 107回答 1
1回答

慕尼黑的夜晚无繁华

json_encode()正是您在这里需要的工具,但您似乎正在与它作斗争,试图撤消它的工作并用您身边的手动工作代替它。正常创建单个数据结构。不要试图编码任何东西。例如// Don't do this:$point['name'] = "'$ride->event_name'";// Do this instead:$point['name'] = $ride->event_name;// Don't do this:array_push($countingRideData, json_encode($point));// Do this instead:array_push($countingRideData, $point);// Remove this altogether:$countingRideDataString = str_replace('"', "", join($countingRideData, ','));编码一次,最后:&nbsp; &nbsp; // Don't do this:&nbsp; &nbsp; data: [<?php echo $countingRideDataString; ?>],&nbsp; &nbsp; // Do this instead:&nbsp; &nbsp; data: <?php echo json_encode(countingRideData); ?>,
打开App,查看更多内容
随时随地看视频慕课网APP