How to send HTML elements through JSON using PHP?

本秂侑毒 提交于 2019-12-11 01:38:14

问题


The following function

    try{
        $query =  $this->pdo->prepare("SELECT * FROM bookings WHERE TourID = ? AND dTourDate = ? and Status NOT LIKE 'Cancelled'");
        $query->execute(array($tourId,$date));
        $result = $query->fetchAll(PDO::FETCH_ASSOC);
        if(count($result)<1)
            $this->error("'Booking' Not Found.",$this->errCode->sqlNotBooking);
        $this->success("Booking List Success.",(array) $result);
    }

returns me this:

 TotalPrice":"0.00","GuestName":"Bryan Pedrochi<\/span>","ContactNumber":"042214"...

The GuestName column in mysql looks like this

<span style="background-color: rgb(255, 255, 0);">Bryan Pedrochi</span>

I am not very good in programming and I am not sure how to do it but I believe I have to place backslash before the double quote in regarding to have a proper result like this

TotalPrice":"0.00","GuestName":"<style=\"background-color: rgb(255, 255, 0);\">Bryan Pedrochi</span>","ContactNumber":"042214"...

So, I tried

$add= $query->fetchAll(PDO::FETCH_ASSOC);
$string=serialize($add); 
$result=addslashes($string); 

I tried

$this->success("Booking List Success.",(array) htmlentities($result));

but nothing seems to work. Is it possible to return HTML elements and backslashes in JSON results?


回答1:


you have to strip the html tags.

try{
    $query =  $this->pdo->prepare("SELECT * FROM bookings WHERE TourID = ? AND dTourDate = ? and Status NOT LIKE 'Cancelled'");
    $query->execute(array($tourId,$date));
    $result = $query->fetchAll(PDO::FETCH_ASSOC);
    $resultStrip = json_decode(strip_tags(json_encode($result)), true);
    if(count($resultStrip )<1)
        $this->error("'Booking' Not Found.",$this->errCode->sqlNotBooking);
    $this->success("Booking List Success.",(array) $resultStrip);
}

hope it helps.



来源:https://stackoverflow.com/questions/47972020/how-to-send-html-elements-through-json-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!