JSON - Avoid UNICODE conversion - php

Why is my string converted to UNICODE in JSON?
http://example.com/test/test.php?MyComment=%C4%93
Saved in JSON as {"MyComment":"\u0113 "}
I want to be saved as {"MyComment":"%C4%93"}
PHP:
$MyComment = $_GET["MyComment"];
print_r($MyComment); //%C4%93
$results = array ( array(
"MyComment" => $MyComment,
));
$inp = file_get_contents('Test.json');
$arr = json_decode($inp);
$results = array_merge($results, $arr);
$fp_login = fopen('Test.json', w);
fwrite($fp_login, json_encode($results));
fclose($fp_login);

If you just want to have the urlencoded value, you have to replace this:
$MyComment = $_GET["MyComment"];
with this (updated due to the comments below):
$MyComment = urlencode( $_GET["MyComment"] );
For your Swift problem you should use :
$MyComment = rawurlencode( $_GET["MyComment"] );
The whitespace will be encoded as %20 so you can decode it at the Swift side.
console output:
Object {MyComment: "%C4%93"}

You have to pass the constant JSON_UNESCAPED_UNICODE to avoid it.
$json = json_encode($data, JSON_UNESCAPED_UNICODE);

In php 5.4+, php's json_encode does have the JSON_UNESCAPED_UNICODE option for plain output. On older php versions, you can roll out your own JSON encoder that does not encode non-ASCII characters.

Related

Extracting data from Json in Php

I have this Json Object Below, I want to extract this data and output it in PHP
{"seat_booked":"A5","0":"A5","1":"A3"}
then get them into this format
$seat_booked = "'A5', 'A5', 'A3'";
How can I do this?
I hope you are looking for this, its very simple example by using json_decode():
$string = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = json_decode($string,true);
$resuiredString = '"'."'".implode("','", $decoded)."'".'"';
echo $resuiredString;
Result:
"'A5','A5','A3'"
Side Note:
I suggest you to learn about variable concatenation.
PHP Concatenation
Another solution:
$json = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = array_map(
function($val) {
return "'". $val."'";
},
array_values(json_decode($json, true))
);
To get an object from a json in php you can use json_decode has explained here.
But you have another problem, your json is wrong!
If you want to represent a single dimensional array you should at least do this
["A5","A5","A3"]
Finally, using json_decode:
$obj = json_decode('["A5","A5","A3"]');
var_dump($obj);
Also, you could do something like:
{"0":"A5","1":"A5","2":"A3"}
$obj = json_decode('{"0":"A5","1":"A3", "2": "A5"}', true);
var_dump($obj);
Edit:
It's not very clear from your question if you are trying to get back an object from a json or if you just want to get a string from it.
If what you need is an string then you don't even need json, you could do this by string manipulation and/or using regex.
But just for completeness, if a quoted comma separated string is what you need you can do this:
$array = json_decode('["A5","A5","A3"]');
$str = implode("','",$array);
$str = "'" . $str . "'";
var_dump($str);

Extract JSON Array from data

I am requesting data from another website and expecting a clean json array in return.
However I am getting this instead:
<pre></pre>{"Status":"Success","Result":1}
which won't parse with json_decode();.
How do I extract the JSON array out of this data so I can parse it?
Note: I am not in control of the code I am requesting the data from.
try this
$output_array = array();
$badstr = '<pre></pre>{"Status":"Success","Result":1}';
preg_match("/{.*}/", $badstr, $output_array);
in $output_array[0] you have your json string.
Assuming that <pre></pre> is constant, then just a simple substring operation:
$badstr = '<pre></pre>{"Status":"Success","Result":1}';
$goodstr = substr($badstr, 11);
But you really should yell at the server admins for sending out bad json in the first place. There's no excuse for this kind of thing. It's probably some debug code they forgot to take out.
If you want it to work both now, and once the issue will be fixed, you can do this:
$result = '<pre></pre>{"Status":"Success","Result":1}';
if (strpos($result ,'<pre>') !== false)
{
$array = json_decode(substr($result , 11));
}
else
{
$array = json_decode($result);
}
Only remove <pre></pre>, only if it's the first thing:
$response = preg_replace('#^<pre></pre>#', '', $response);
How about simply string replace?
Like so:
$json_string = '<pre></pre>{"Status":"Success","Result":1}';
$json = str_replace("<pre></pre>", "", $json_string);
echo $json;
Output:
{"Status":"Success","Result":1}
If you don't expect any html tags in your output, you can also use strip_tags():
$not_json = '<pre></pre>{"Status":"Success","Result":1}';
$json_string = strip_tags($json);
$result = json_decode($json_string);

json_decode($data, true); doesn't work

I'm trying to access stock Quotes through Google Finance
by doing so:
$quote = file_get_contents('http://finance.google.com/finance/info?client=ig&q=VSE:APG1L');
$json = str_replace("\n", "", $quote);
$data = substr($json, 4, strlen($json) -5);
print_r($data);
$json_output = json_decode($data, true);
print_r($json_output);
echo "\n".$json_output['l'];
json_decode suppose to give me an normal array with keys and values, but it doesn't.
If you look at json_last_error() after attempting json_decode() you'll see that you are getting:
JSON_ERROR_UTF8 Malformed UTF-8 characters, possibly incorrectly encoded
Try this:
$quote = file_get_contents('http://finance.google.com/finance/info?client=ig&q=VSE:APG1L');
$json = substr($quote, 4, -5);
$json_output = json_decode($json, true, JSON_UNESCAPED_UNICODE);
print_r($json_output);
See: http://3v4l.org/jkInl
Note that JSON_UNESCAPED_UNICODE is only available as of php 5.4
Another option would be to do...
$quote = utf8_decode($quote);
...after you fetch it. This will convert the euro symbol into a ? character. Might not be what you want, but at least you get json_decode to return an array to you.
Update: See here for more information:
PHP decoding and encoding json with unicode characters
Another solution is to "manually" replace all instances of € by \u20AC (which is the unicode character point for the Euro sign).
$quote = file_get_contents('http://finance.google.com/finance/info?client=ig&q=VSE:APG1L');
$quote = str_replace(chr(128), '\u20AC', $quote);
$json = substr($quote, 6, -3); // remove unnecessary '// [ … ]'
$json_output = json_decode($json, true);
print_r($json_output);

How to Encode URL Contains Unicode Characters with PHP

Currently, I'm trying to look for a solution to encode url which contains unicode characters, Khmer Unicode. I've tried using php built-in function urlencode() and it gives result:
For example: http://www.example.com/?kwd=Mac+Book+Pro+នៅប្រទេសយើង
While I've tested with Google search, it results:
https://www.google.com.kh/#hl=en&sclient=psy-ab&q=Mac+Book+Pro+%E1%9E%93%E1%9F%85%E1%9E%94%E1%9F%92%E1%9E%9A%E1%9E%91%E1%9F%81%E1%9E%9F%E1%9E%99%E1%9E%BE%E1%9E%84&oq=Mac+Book+Pro+%E1%9E%93%E1%9F%85%E1%9E%94%E1%9F%92%E1%9E%9A%E1%9E%91%E1%9F%81%E1%9E%9F%E1%9E%99%E1%9E%BE%E1%9E%84
How to do that? Hope someone here would help me.
Thanks in advance!
For UTF-8 you can use:
urlencode(utf8_encode($string)); //for encoding
utf8_decode(urldecode($string)); //for decoding
For UTF-16 you can use this function (from notes for urlencode in http://php.net/urlencode):
function utf16_urlencode ( $str ) {
# convert characters > 255 into HTML entities
$convmap = array( 0xFF, 0x2FFFF, 0, 0xFFFF );
$str = mb_encode_numericentity( $str, $convmap, "UTF-8");
# escape HTML entities, so they are not urlencoded
$str = preg_replace( '/&#([0-9a-fA-F]{2,5});/i', 'mark\\1mark', $str );
$str = urlencode($str);
# now convert escaped entities into unicode url syntax
$str = preg_replace( '/mark([0-9a-fA-F]{2,5})mark/i', '%u\\1', $str );
return $str;
}
function cleanUrl($url) {
$res= urlencode(utf8_encode($url));
$res = str_replace("%3A",":",$res);
$res = str_replace("%2F","/",$res);
return $res;
}
Try rawurlencode
http://php.net/manual/en/function.rawurlencode.php

decode url with php

how can I decode following query string with php?
t=%B1Z%2B%26k%C9%BF%B1%3Fh%3Fd%3F%9F%2Fa%90%3Ft%C5%8B%A0%3F-%F9s%D5d+%E2sJ-B%9DE%D0T%FA%A4.%93%AF%A05%98d%F9%85%CC%22H%3Fd%F9%9D%C3%22hE%8B%C1%D65%3F%A8%3A%25%24&charset=ISO-8859-1
I've already tried urldecode but I get following output
t=±Z+&kÉ¿±?h?d?Ÿ/a?tÅ‹ ?-ùsÕd âsJ-BEÐTú¤.“¯ 5˜dù…Ì"H?dùÃ"hE‹ÁÖ5?¨:%$&charset=ISO-8859-1
I've tried many ways but couldn't decode it
thanks in advance
Use parse_str to "decode" and parse your string, as in the example snippet further down in this post.
Read more about the function in php.net's manual:
PHP: parse_str - Manual
$data = "t=%B1Z%2B%26k%C9%BF%B1%3Fh%3Fd%3F%9F%2Fa%90%3Ft%C5%8B%A0%3F-%F9s%D5d+%E2sJ-B%9DE%D0T%FA%A4.%93%AF%A05%98d%F9%85%CC%22H%3Fd%F9%9D%C3%22hE%8B%C1%D65%3F%A8%3A%25%24&charset=ISO-8859-1";
parse_str ($data, $out);
print_r ($out);
Array
(
[t] => ±Z+&kÉ¿±?h?d?/a?tÅ ?-ùsÕd âsJ-BEÐTú¤.¯ 5dùÌ\"H?dùÃ\"hEÁÖ5?¨:%$
[charset] => ISO-8859-1
)
Read about urlencode and urldecode here
$output = urldecode($encoded);
Use urldecode!
$decoded = urldecode(substr($queryString,3));
maybe this one might help:
<?php
$variable = 'http%3A%2F%2Fsample.com';
$variable = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($variable));
$variable = html_entity_decode($variable,null,'UTF-8');
echo $variable;
?>
output will be : http://sample.com

Categories