php - Decoding string... to array format -
i'm trying decode return string array... dont know whether json format or not return code this.. doing wrong?
[ [ ["संकल्प", "resolution", "saṅkalpa", ""] ], [ ["noun", ["प्रस्ताव", "संकल्प", "समाधान", "स्थिरता", "चित्त की दृढ़ता", "प्रण"], [ ["प्रस्ताव", ["offer", "proposal", "motion", "resolution", "proposition", "offering"], , 0.69811249], ["संकल्प", ["resolution", "resolve", "determination", "pledge", "solemn vow"], , 0.53526145], ["समाधान", ["solution", "resolution", "settlement", "key", "resolvent", "redress"], , 0.064934582], ["स्थिरता", ["stability", "fixture", "fastness", "durability", "serenity", "resolution"], , 4.8327973e-05], ["चित्त की दृढ़ता", ["resolution", "strong will"], , 4.7578716e-05], ["प्रण", ["pledge", "vow", "capitulation", "determination", "resolution"], , 4.7578716e-05] ] ] ], "en", , [ ["संकल्प", [4], 1, 0, 999, 0, 1, 0] ], [ ["resolution", 4, [ ["संकल्प", 999, 1, 0], ["प्रस्ताव", 0, 1, 0], ["समाधान", 0, 1, 0], ["संकल्प के", 0, 1, 0], ["संकल्प में", 0, 1, 0] ], [ [0, 10] ], "resolution" ] ], , , [ ["en"] ], 5 ]
php code..
<html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> </head> <body> <?php ini_set ( 'display_errors', 1 ); error_reporting ( e_all ); //text $text = 'resolution'; $text = trim ( $text ); //language code hi => hindi $tl = 'hi'; $data = file_get_contents ( "http://translate.google.com/translate_a/t?ie=utf-8&oe=utf-8&client=t&sl=en&tl=" . $tl . "&sc=1&text=" . $text ); echo '<pre>'; print_r ( $data ); echo '</pre> <hr/>'; echo '<pre>'; var_dump ( json_decode ( $data, true ) ); echo '</pre>'; ?> </body> </html>
the problem input string there consecutive (ignoring whitespace) commas. manually correcting them in jsonlint yields valid json.
a simple (albeit crude) solution replace occurrences of more 1 consecutive comma (i.e. ,,
or ,,,
, etc) single comma. jsonlint validates string valid json, , json_decode()
returns array, should.
a regex replace should trick:
$string = "[ 'json' ]"; $string = preg_replace('/,(\s*,)+/', ',', $string); $arr = json_decode($string);
$arr
array (not object may assume) representing json data.
Comments
Post a Comment