how to encode raw json string in php - php

I have JSON that has been saved in a text box on my site to a database below.
{"#type":"GOOOGLE.COM","#id":"GOOGLE","url":"GOOGLE","inLanguage":"en-US","name":"dfghjk | Bloomberg Professional Services","isPartOf":{"#id":"GOOGLE,"datePublished":"2020-02-11T21:51:45+00:00","dateModified":"2020-02-11T21:51:45+00:00"}]}
I want to convert it to look properly in PHP as so:
{"#type":"GOOOGLE.COM","#id":"GOOGLE","url":"GOOGLE","inLanguage":"en-US","name":"dfghjk | Bloomberg Professional Services","isPartOf":{"#id":"GOOGLE,"datePublished":"2020-02-11T21:51:45+00:00","dateModified":"2020-02-11T21:51:45+00:00"}]}
I tried doing a json_encode but its not working. How do i convert that string with all those escape quotes etc to a normal json string in PHP?
I tried as so:
$str = "{"#type":"GOOOGLE.COM","#id":"GOOGLE","url":"GOOGLE","inLanguage":"en-US","name":"dfghjk | Bloomberg Professional Services","isPartOf":{"#id":"GOOGLE,"datePublished":"2020-02-11T21:51:45+00:00","dateModified":"2020-02-11T21:51:45+00:00"}]}"
$data = json_encode($str, true);
return $data;

You need to decode HTML entities back into characters:
https://www.php.net/manual/en/function.htmlspecialchars-decode.php
$json = htmlspecialchars_decode($str, true); // valid json string
$data = json_decode($json); // convert json to php data structure
return $data;

Related

Encode to base64 with Php gives different result than with Python 3

I am trying to convert a code in Php to Python, it consists of encoding a variable obtained with the chr function with base64 using the base64_encode function.
Here is the code in Php:
$data = chr(ord('a')+ord('b'));
$data = base64_encode($data);
echo $data;
result:
ww==
Here is what I tried to do in Python:
from base64 import b64encode
data = chr(ord('a')+ord('b'))
data = b64encode(data.encode()) // data.encode() is mandatory or I get an error saying that b64encode require a bytes-like object
print(data)
result:
b'w4M='
Thank you for your help
Aymeric
I don't know if it's the real answer to the question, but the problem is that python string from version 3 are in unicode. so the php-code can be replaced:
<?php
$data = chr(ord('a')+ord('b'));
$data = utf8_encode($data);
echo base64_encode($data); //w4M=
or you can use https://www.php.net/manual/en/function.mb-chr.php for this
so for changing python code to work it as php - you need to encode data in latin-1:
from base64 import b64encode
data = chr(ord('a')+ord('b')).encode('latin-1')
data = b64encode(data)
print(data) # b'ww=='
print(data.decode()) # ww==

PHP decode JSON from Android

I post a JSON from Android to PHP:
{"0":{"nome":"name","cf":"0101","address":"STREET 123"},"1":{"codice":"123","nome":"ACQUA","quantita":"3"},"2":{"codice":"123","nome":"ACQUA","quantita":"3"}}
In php i need to get user info always 0 (nome, cf and address) after this i need a while for getting dynamic element 1,2,3,4 etc etc (in while) always codice, nome and quantita but i have tried some code in php like:
$string = {"0":{"nome":"name","cf":"0101","address":"STREET 123"},"1":{"codice":"123","nome":"ACQUA","quantita":"3"},"2":{"codice":"123","nome":"ACQUA","quantita":"3"}};
$string = json_encode($string);
$nome = json_decode ($string, true);
echo $nome[0]->nome; //for single user info
but result is always white page
There are a few mistakes in the code...
$string = '{"0":{"nome":"name","cf":"0101","address":"STREET 123"},"1":{"codice":"123","nome":"ACQUA","quantita":"3"},"2":{"codice":"123","nome":"ACQUA","quantita":"3"}}';
//$string = json_encode($string);
$nome = json_decode ($string, true);
echo $nome[0]['nome']; //for single user info
The first line needs single quotes round it.
The json_encode() isn't needed as it's already JSON.
The last line needs to use ['nome'] as it's using arrays (by using true as the second parameter to json_decode())

PHP: How to json encode of hindi language in response

I am working with a translation API but here is an issue. I am using JSON in response and when I do json_encode of Hindi then the out is like "\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948"
My code is given below
$data = array();
$data['hindi'] = 'यह कार है';
$data['english'] = 'This is car';
echo json_encode($data); die;
and the response is
{"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"}
If you are running PHP 5.4 or greater, pass the JSON_UNESCAPED_UNICODEparameter when calling json_encode
Example:
$data = array();
$data['hindi'] = 'यह कार है';
$data['english'] = 'This is car';
echo json_encode($data, JSON_UNESCAPED_UNICODE);
die;
This is correct json and when you display it in the browser and / or parse it, it will result in an object with the correct keys and values:
var json_string = '{"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"}',
json = JSON.parse(json_string);
// or directly:
var json2 = {"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"};
console.log(json_string);
console.log(json);
console.log(json2);
document.write(json_string);
document.write('<br>');
document.write(json.hindi);
document.write('<br>');
document.write(json2.hindi);
The reason for this is likely that these characters are not in UTF-8 (I could not find them, at least). From the PHP documentation on json_encode:
All string data must be UTF-8 encoded.
This means that it will have to convert it to a 'description' of the characters. Do not worry, if you decode it again it will very likely be correct.
I have a solution to this problem. It works fine for me.
$data = array();
$data['hindi'] = base64_encode('यह कार है');
$data['english'] = 'This is car';
$encoded_text=json_encode($data);
To retrieve the hindi part of data:
$hindi=base64_decode(json_decode($encoded_text)->hindi);

Parsing JSON in PHP with a prepend of sorts

if my JSON data is coming back as this:
{"errorCodes":[0]}resultArray=[{....}]
how do I grab the resultArray as the actual JSON string and ignore the rest?
and why would I need errorCodes in front of it?
Just use string manipulation to get rid of everything up through resultArray= and then decode with json_decode().
$json_raw = '...'; // the raw "JSON" string
$delimiter = 'resultArray=';
$cleaned_json = substr($json_raw, strpos($json_raw,$delimiter) + strlen($delimiter)));
$object = json_decode($cleaned_json);

Extract Data from JSON URL

http://www.instamapper.com/api?action=getPositions&key=584014439054448247&num=10&format=json
is the url, which contains json data. I want to use that data and send SMS to a particular phone no if value of latitude and longitude(Extracted from JSON).
Check constraints, we can use through php. But the main problem is How to extract data from JSON file?
I don't want to give you the solution, so the below should be enough to get you started.
Read in the JSON data using file_get_contents
Parse the JSON string into a PHP object using json_decode
Your code should look something like this:
$url = "http://www.instamapper.com/api?action=getPositions&key=584014439054448247&num=10&format=json";
$contents = file_get_contents($url);
$jsonObj = json_decode($contents);
You mean something like this?
<?php
$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
foreach ( $json_output->trends as $trend )
{
echo "{$trend->name}\n";
}

Categories