2

Trying to save data with specials characters using json_encode.

Code sample:

$a = array("Name" => "SáENZ PEñA");
echo "Normal : ",  json_encode($a), "<br>";
echo "Unicode : ", json_encode($a, JSON_UNESCAPED_UNICODE), "<br>";

JSON_UNESCAPED_UNICODE solve the issue with php 5.6

Normal : {"Name":"S\u00e1ENZ PE\u00f1A"}
Unicode : {"Name":"SáENZ PEñA"}

but unfortunelly i have php 5.3 :

Normal : {"Name":"S\u00e1ENZ PE\u00f1A"}
Unicode : 
Warning: json_encode() expects parameter 2 to be long, string given in /var/www/.../TEST.php on line 4

Any solution that works with php 5.3 ?

2
  • why you are passing already encoded data to re-encode again? pass array Commented Sep 27, 2016 at 12:11
  • To save data in a json file with fwrite Commented Sep 27, 2016 at 12:13

1 Answer 1

1

If you can't use JSON_UNESCAPED_UNICODE, you could probably unescape the JSON yourself after it's been encoded:

  • Compatible with \ (escaped backslashes itself)
  • Compatible with JSON_HEX_* flags

    function raw_json_encode($input, $flags = 0) { $fails = implode('|', array_filter(array( '\\\\', $flags & JSON_HEX_TAG ? 'u003[CE]' : '', $flags & JSON_HEX_AMP ? 'u0026' : '', $flags & JSON_HEX_APOS ? 'u0027' : '', $flags & JSON_HEX_QUOT ? 'u0022' : '', ))); $pattern = "/\\\\(?:(?:$fails)(*SKIP)(*FAIL)|u([0-9a-fA-F]{4}))/"; $callback = function ($m) { return html_entity_decode("&#x$m[1];", ENT_QUOTES, 'UTF-8'); }; return preg_replace_callback($pattern, $callback, json_encode($input, $flags)); }

Example

<?php

function raw_json_encode($input, $flags = 0) {
    $fails = implode('|', array_filter(array(
        '\\\\',
        $flags & JSON_HEX_TAG ? 'u003[CE]' : '',
        $flags & JSON_HEX_AMP ? 'u0026' : '',
        $flags & JSON_HEX_APOS ? 'u0027' : '',
        $flags & JSON_HEX_QUOT ? 'u0022' : '',
    )));
    $pattern = "/\\\\(?:(?:$fails)(*SKIP)(*FAIL)|u([0-9a-fA-F]{4}))/";
    $callback = function ($m) {
        return html_entity_decode("&#x$m[1];", ENT_QUOTES, 'UTF-8');
    };
    return preg_replace_callback($pattern, $callback, json_encode($input, $flags));
}

$json = array(
    'Sample' => array(
        'specialchars' => '<x>& \' "</x>',
        'backslashes' => '\\u0020',
        'context' => 'جمهوری اسلامی ایران',
    )
);

echo raw_json_encode($json, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);

/* 
{"Sample":{"specialchars":"\u003Cx\u003E\u0026 \u0027 \u0022\u003C\/x\u003E","backslashes":"\\u0020","context":"جمهوری اسلامی ایران"}}
*/
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.