JSON code to Array - quotes and double quotes - php

I have a big JSON code - 2 801 278 characters. Now I want to create an array from this JSON code in my PHP script, but I can't because my script has quotes and double quotes and PHP return an error. Here is a simply code which do the same problem:
{"title":"Example string's with \"special\" characters"}
As you can see, when I paste this code in that way:
var_dump(json_decode('{"title":"Example string's with \"special\" characters"}', true));
I got an error because ' is not escaped. When I try to change change string's for string\'s, I got:
Recoverable fatal error: Object of class stdClass could not be
converted to string in...
How I should change this JSON code to correctly create an array?

You can do one of two things.
Read JSON from a file. (Recommended)
Use Heredoc.
Reading JSON from a File
Have a file next to your PHP file that has the JSON and read it using file_get_contents().
<?php
$json = file_get_contents("file.json");
$array = json_decode($json, true);
?>
Using Heredoc
<?php
$json = <<<EOD
{"title":"Example string's with \"special\" characters"}
EOD;
$array = json_decode($json, true);
?>
Demo: https://eval.in/1119967
Both the above methods yield the same output.

Related

How to remove backslashes from json response in php

I am getting json response as mentioned below:
"{\"id\":\"order_DPUVoS2YVnBccy\",\"entity\":\"order\",\"amount\":100,\"amount_paid\":0,\"amount_due\":100,\"currency\":\"INR\",\"receipt\":\"7550\",\"offer_id\":null,\"status\":\"created\",\"attempts\":0,\"notes\":[],\"created_at\":1570082483}"
I want output to be as:
{"id":"order_DPUVoS2YVnBccy","entity":"order","amount":100,"amount_paid":0,"amount_due":100,"currency":"INR","receipt":"7550","offer_id":null,"status":"created","attempts":0,"notes":[],"created_at":1570082483}
I tried using stripslashes() to remove backslashes, but its not working.
What do you mean by "not working"?
<?php
$unescapedJson = '{\"id\":\"order_DPUVoS2YVnBccy\",\"entity\":\"order\",\"amount\":100,\"amount_paid\":0,\"amount_due\":100,\"currency\":\"INR\",\"receipt\":\"7550\",\"offer_id\":null,\"status\":\"created\",\"attempts\":0,\"notes\":[],\"created_at\":1570082483}';
echo stripslashes($unescapedJson);
Output for PHP 7.1.25 - 7.4.0rc2:
{"id":"order_DPUVoS2YVnBccy","entity":"order","amount":100,"amount_paid":0,"amount_due":100,"currency":"INR","receipt":"7550","offer_id":null,"status":"created","attempts":0,"notes":[],"created_at":1570082483}
you have to do it when json decode:
$data = json_encode('yourjsonvariable'), true, JSON_UNESCAPED_SLASHES);

Formatting JSON formatted text file in PHP

So I got a HTML page with a button. When I click the button, a separate javascript file sends a GET request to my PHP file, expecting a JSON object in return. My PHP reads a JSON formatted text file and should convert it into a JSONObject and echo it out for my javascipt. I had some code working before, but it doesn't seem to do it anymore since I changed to a Ajax aproach instead of having everything in the same file. This is my code:
readLog.php
<?php
class test{
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
function getLog(){
header('Content-Type: application/json');
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
echo json_encode($logLines);
}
}
?>
My humid.log file looks like this:
{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }
{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }
Now If I press my button, this is the response I get checking the console in my web browser:
Response:
["{\"date\":\"26\/09\/2016\", \"time\":\"22:40:46\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }{\"date\":\"26\/09\/2016\", \"time\":\"23:10:47\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }\n"]
JSON:
"{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }\n"
obviously something is wrong with the formatting, but I don't know what. As I said, this code worked just fine when I had my php and HTML in the same file.
EDIT:
I have also tried formatting the JSON with something like this, but it just prints the brackets:
function getLog(){
$text = file('../../../home/shares/flower_hum/humid.log');
$textRemoved ="["; //Add opening bracket.
$textRemoved .= substr($text, 0, strlen($text)-1); (Remove last comma)
$textRemoved .="]";//Add closing bracket
$json = json_encode($textRemoved);
echo $json;
}
So I managed to solve it myself. Basicly The formatting of the textfile was wrong and as some commentors said, I don't need to encode it if I am doing it myself. What I ended up doing was in my application that generates the log file to add comma after each row. Then in my PHP I added brackets and removed the last comma.
function getLog(){
header('Content-Type: application/json');
$file = file_get_contents('../../../home/shares/flower_hum/humid.log');
$lengthOfFile = strlen($file)-2;
$subFile = substr($file, 0, $lengthOfFile);
$res ="[";
$res .= $subFile;
$res .="]";
echo $res;
}
You can't just jam two+ JSON strings togther. It's JSON, which means it HAS to be syntactically correct Javascript CODE. If you want to join two json strings together, you HAVE to decode them to a native data structure, join those structures together, then re-encode the new merged structure:
$temp1 = json_decode('{"foo":"bar"}', true);
$temp2 = json_decode('{"baz":"qux"}', true);
$new = array_merge($temp1, $temp2);
echo json_encode($new);
which will produce:
{"foo":"bar","baz":"qux"}
and remain valid JSON/Javascript.
Why? Consider that bare integers are valid json:
json_encode(42) -> 42
json_encode(123) -> 123
If you have two json-encoded integers and jam together, you get a "new" integer:
42123
and on the receiving end, you'll be going "Ok, so where is the split between the two", because 4 and 2123 are just as valid as possible original values as 4212 and 3.
Sending the two integers as distinct and SEPARATABLE values would require an array:
[42,123]

SimpleXMLElement using a string

I want to create a new SimpleXMLElement with data . When I put the data from the link below in the code I get the next error: Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML
The encoded data can be found here:http://www.interwebmedia.nl/dataxi/base64.txt
decoded data: http://www.interwebmedia.nl/dataxi/data.txt
<?php
str = 'encodeddata';
//echo htmlspecialchars(base64_decode($str),ENT_QUOTES);
$decoded = htmlspecialchars(base64_decode($str),ENT_QUOTES);
$xml = new SimpleXMLElement($decode);
echo $xml->asXML();
?>
I think you've attempted to use HEREDOC syntax (or seen somebody else using it) but completely misunderstood it.
HEREDOC syntax is an alternative way of quoting a string, instead of " or '. It's useful for hard-coding blocks of XML, because it acts like double-quotes, but let's you use double-quotes inside, like this:
$my_xml_string = <<<XML
<some_xml>
<with multiple_lines="here" />
</some_xml>
XML;
That code is precisely equivalent to this:
$my_xml_string = "
<some_xml>
<with multiple_lines=\"here\" />
</some_xml>
";
What you have done instead is taken the literal string "<<<" and added it onto your XML, giving you a string like this:
$my_xml_string = "<<<XML
<some_xml>
<with multiple_lines=\"here\" />
</some_xml>
XML";
Or in your example, the string "<<<XML<data>XML".
As far as the XML parser's concerned, you've just put a load of garbage on the beginning and end of the string, so it rightly complains it's not a valid XML document.

simplexml_load_string and the unwelcome parse error

Update: Casting as an array does the trick. See this response, since I don't have enough clout to upvote :)
I started on this problem with many potential culprits, but after lots of diagnostics the problem is still there and no obvious answers remain.
I want to print the placename "Gaborone", which is located at the first tag under the first tag under the first tag of this API-loaded XML file. How can I parse this to return that content?
<?php
# load the XML file
$test1 = (string)file_get_contents('http://www.afdb.org/fileadmin/uploads/afdb/Documents/Generic-Documents/IATIBotswanaData.xml');
#throw it into simplexml for parsing
$xmlfile = simplexml_load_string($test1);
#output the parsed text
echo $xmlfile->iati-activity[0]->location[0]->gazetteer-entry;
?>
Which never fails to return this:
Parse error: syntax error, unexpected '[', expecting ',' or ';'
I've tried changing the syntax to avoid the hyphens in the tag names as such:
echo $xmlfile["iati-activity"][0]["location"][0]["gazetteer-entry"];
. . . but that returns complete nothingness; no error, no source.
I've also tried debugging based on these otherwise-helpful threads, but none of the solutions have worked. Is there an obvious error in my simplexml addressing?
I've tried changing the syntax to avoid the hyphens in the tag names
as such: echo
$xmlfile["iati-activity"][0]["location"][0]["gazetteer-entry"];
Your problem here is that, object native casting to an array isn't recursive, so that you did that for primary keys only. And yes, your guess is correct - you shouldn't deal with object properties when working with returned value of simplexml_load_string() because of the syntax issues. Instead, you should cast a returned value of it (stdclass) into an array recursively. You can use this function for that:
function object2array($object) {
return json_decode(json_encode($object), true);
}
The rest:
// load the XML file
$test1 = file_get_contents('http://www.afdb.org/fileadmin/uploads/afdb/Documents/Generic-Documents/IATIBotswanaData.xml');
$xml = simplexml_load_string($test1);
// Cast an object into array, that makes it much easier to work with
$data = object2array($xml);
$data = $data['iati-activity'][0]['location'][0]['gazetteer-entry']; // Works
var_dump($data); // string(8) "Gaborone"
I had a similar problem parsing XML using the simpleXML command until I did the following string replacements:
//$response contains the XML string
$response = str_replace(array("\n", "\r", "\t"), '', $response); //eliminate newlines, carriage returns and tabs
$response = trim(str_replace('"', "'", $response)); // turn double quotes into single quotes
$simpleXml = simplexml_load_string($response);
$json = json_decode(json_encode($simpleXml)); // an extra step I took so I got it into a nice object that is easy to parse and navigate
If that doesn't work, there's some talk over at PHP about CDATA not always being handled properly - PHP version dependent.
You could try this code prior to calling the simplexml_load_string function:
if(strpos($content, '<![CDATA[')) {
function parseCDATA($data) {
return htmlentities($data[1]);
}
$content = preg_replace_callback(
'#<!\[CDATA\[(.*)\]\]>#',
'parseCDATA',
str_replace("\n", " ", $content)
);
}
I've reread this, and I think your error is happening on your final line - try this:
echo $xmlfile->{'iati-activity'}[0]->location[0]->{'gazetteer-entry'};

json inside function, (php parsing)

I have sth like that inside *.txt file.
function_name({"one": {"id": "id_for_one", "value": "value_for_one"}, ...});
And I am getting the file like this:
$source = 'FILE_NAME.txt';
$json = json_decode(file_get_contents($source),true);
echo $json['one']['value'];
It doesn't work, but when I remove function_name( and ); it works.
How to parse it without removing these strings?
You can't. It is not valid JSON with those. Take a substring that excludes them.
You will have to remove those strings. With the function_name portion it is not valid JSON.
A JSON string will typically either begin with { (object notation) or [ (array notation), but can also be scalar values such as a string or number. You cannot parse it without first making sure the string is valid JSON.
You are trying to get the string within a file and decoding it as a JSON file.
The 'function_name' isn't a valid JSON string, the rest inside yes.
How to parse it without removing these strings?
There is no way.
This should work for you.
$data = file_get_contents($source);
$data = substr($data, strlen("function_name("));
$data{strlen($data)-1}=$data{strlen($data)-2}=" ";
$json = json_decode($data,true);
Both {} and [] works for string to access individual characters.
The function in your text file, means that isn't a json file.
Remove the string using a regular expression, and your problem is fixed.
If the function is a fixed name, do something like this:
$source = 'FILE_NAME.txt';
$json_content = str_replace('function_name(', '', file_get_contents($source));
$json_content = substr($json_content,0,-2);
$json = json_decode($json_content,true);
echo $json['one']['value'];

Categories