PHP JSON String, escape Double Quotes for JS output

后端 未结 7 1135
旧时难觅i
旧时难觅i 2020-11-29 04:44

I\'m creating a JSON string from a PHP array. I\'ve encoded it using json_encode().

$data = array(
    \'title\' => \'Example string\\\'s wit         


        
7条回答
  •  青春惊慌失措
    2020-11-29 05:38

    I had challenge with users innocently entering € and some using double quotes to define their content. I tweaked a couple of answers from this page and others to finally define my small little work-around

    $products = array($ofDirtyArray);
    if($products !=null) {
        header("Content-type: application/json");
        header('Content-Type: charset=utf-8');
        array_walk_recursive($products, function(&$val) {
            $val = html_entity_decode(htmlentities($val, ENT_QUOTES, "UTF-8"));
        });
        echo json_encode($products,  JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
    }
    

    I hope it helps someone/someone improves it.

提交回复
热议问题