Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php escape special characters in a JSON string

Tags:

json

arrays

php

I have an array of product details, in the product_description string I want to escape some special characters such as: " , \ ..etc but I don't know what should I write exactly to do so, what I did was:

json_encode($array[ProductData][Product_description]);

but then when I checked the result, it gives me errors regarding those special characters.

Here's the product description string:

The 30" Apple Cinema HD Display deliver..etc

The error is in the double-quote.

Can you please assist me on how to do it. Thank you

like image 544
Alladin Avatar asked May 24 '26 00:05

Alladin


1 Answers

You can try with

    $value = json_encode($array[ProductData][Product_description]);
    $escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
    $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
    $result = str_replace($escapers, $replacements, $value);

    echo '<pre>';
    print_r($result);
    echo '<pre>';

This is the reference

PHP's json_encode does not escape all JSON control characters

like image 79
Josua Marcel C Avatar answered May 26 '26 13:05

Josua Marcel C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!