代码之家  ›  专栏  ›  技术社区  ›  Johnny

如何使用PHP通过JSON发送HTML元素?

  •  2
  • Johnny  · 技术社区  · 7 年前

    以下功能

        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);
        }
    

    将此返回给我:

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

    mysql中的GuestName列如下所示

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

    我在编程方面不是很好,我不知道怎么做,但我相信我必须在双引号之前加反斜杠,这样才能得到一个合适的结果

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

    所以我试过了

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

    我试过了

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

    但似乎什么都不管用。是否可以在JSON结果中返回HTML元素和反斜杠?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Johnny    7 年前

    你必须去掉html标签。

    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);
    }
    

    希望有帮助。