How to send HTML elements through JSON using PHP?

2019-07-10 00:31发布

问题:

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.