1

I am using ajax call on a PHP file which contains folling code:

echo str_replace(array("\x1e", "\x1c"), "", file_get_contents('http://www.domain.com/getJsonDocuments?categoryBranch='.intval($_GET['category'])));

The problem now is that in those JSON Documents, there are many invisible or special Characters not only the two you can see in code above, which I already str_replace:

array("\x1e", "\x1c")

If I do not replace them, the error function of the ajax call is fired:

$.ajax({
            type: 'GET',
            url: 'jsonrequestCategory.php',
            dataType: 'json',
            success: function(data) {
                console.log('success');
            },
            error: function() {
                console.log('error');
            }
        });

So my question is:

Is there a way to get rid of all those characters somehow? Or do I need to check every Document and every char to avoid getting an error?

ggzone
  • 3,465
  • 7
  • 34
  • 58
  • http://stackoverflow.com/questions/10448060/send-special-characters-with-ajax-and-receive-them-correctly-to-php – Nouphal.M Jan 03 '14 at 10:27
  • encoding in JSON server side doesn't remove these special chars??? – A. Wolff Jan 03 '14 at 10:33
  • The JSON server is from the customer. I prefer "fixing" this in my code first. If theres no other way I will tell the customer to get rid of those characters. – ggzone Jan 03 '14 at 10:37

3 Answers3

2

With preg_replace and a set of Regular Expressions you can replace all control characters as well.

$content = file_get_contents('http://www.domain.com/getJsonDocuments?categoryBranch='.intval($_GET['category']));
$content = preg_replace('/[[:cntrl:]]/', '', $content);

[:cntrl:] will match control characters.

revo
  • 43,830
  • 14
  • 67
  • 109
0

You'll need to use regex on the server side.

$subject = "abcdef";
$pattern = '/[\xA0\x00-\x09\x0B\x0C\x0E-\x1F\x7F]+(.+)[\xA0\x00-\x09\x0B\x0C\x0E-\x1F\x7F]+(.+)/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);

(http://webcheatsheet.com/php/regular_expressions.php)

EoiFirst
  • 1,576
  • 1
  • 15
  • 33
0

JSON does support UTF-8 but it doesn't support binary data (for example: msgpack does). You can however, encode your binary data using base64 (which results in a string) and use that in your response.

In PHP you can use:

base64_encode(...)

In almost every major webbrowser (except IE < 10) you can use:

window.atob(...)

Note that your browser probably isn't able to show non UTF-8 characters either.

elslooo
  • 9,814
  • 3
  • 37
  • 57
  • You did do `base64_encode(file_get_contents(...))`, right? You can use some additional code to support IE 7 as well (see http://stackoverflow.com/a/246813/130580) – elslooo Jan 03 '14 at 10:43
  • yes i did. doesnt work. Your JS solution is maybe a way, i will take a look at it, but if possible i prefer a PHP solution. thanks anyway – ggzone Jan 03 '14 at 10:45