Is there a way to convert to json object in php - php

I have this in my text tile
[{"id":20,"tokenType":"Keyfob","tokenValue":"9037119","isLost":false}][{"id":22,"tokenType":"Keyfob","tokenValue":"47690743","isLost":false}]
But i am trying to convert it to json object like this below:
$cache_file = $_SERVER['DOCUMENT_ROOT']."/site/users/sample-keys-test.txt";
$file = fopen($cache_file, "r");
$file_content = fread($file, filesize($cache_file));
$file_content = preg_replace("/\[(.*?)\]/", "$1,", $file_content);
$file_content = rtrim($file_content, ",");
$data = json_decode("{\"items\": [".$file_content."]}", true);
var_dump($data);
foreach($data["items"] as $json_object) {
// Do something with each JSON object
echo $json_object["id"]."<br>";
echo $json_object["tokenType"]."<br>";
echo $json_object["tokenValue"]."<br>";
echo $json_object["isLost"]."<br>";
}
fclose($file);
But in the line with var_dump i get null which means there is something wrong with converting it to json object.

Related

Convert string to JSON and save as .json file in php

I have a JSON Object. I converted it to string to send data to another page.
I again want to convert that data to JSON and store in a JSON file.
dwv.min.js:
this.onStateSave=function(){
var e=new H.State;
var new_json = e.toJSON(o);
var myJSON = JSON.stringify(new_json);
jQuery.post("add_annotation_script.php",
{myJSON:myJSON}
);
}
add_annotation_script:
$myJSON = (String)$_POST['myJSON'];
$rad = $_SESSION['rad_id'];
$image = $_SESSION['image'];
$case_id = $_SESSION['case_id'];
$jObj = json_decode($myJSON);
$path = "C:/wamp64/www/MIC/anno/".$case_id."/".$image.$case_id.".json";
$f = (file_exists($path))? fopen($path, "a+") : fopen($path, "w+");
fwrite($f, $jObj);
fclose($f);
Is this correct or I am missing anything out?
Errors:
Undefined index: myJSON

modify json object in php

I have a json file which is read by php and i want to change one object of the json file using php now my code looks like this but it doesn't work so how should I do? (the obj_name in the son object should be modified to $name)
<?php
$json = $_POST['myobj'];
$data = json_decode($json,true);
$name = xxxxxxxxx;
$data['obj_name'] = "$name";
#json = json_encode($data);
$filename = xxxxxxxxxxxxx
$file = fopen($filename,'w+');
fwrite($file, $json);
fclose($file);
?>
The # is commenting out your code and it should be a $ to make it a variable.
So, change this:
#json = json_encode($data);
to this:
$json = json_encode($data);

What is the proper way to parse yahoo currency http://finance.yahoo.com/connection/currency-converter-cache?date?

As the code i tried and by trial removal to get json content out of the return is below
method i used.
$date= YYYYMMDD;
//example '20140113'
$handle = fopen('http://finance.yahoo.com/connection/currency-converter-cache?date='.$date.'', 'r');
//sample code is http://finance.yahoo.com/connection/currency-converter-cache?date=20140208 paste the url in browser;
// use loop to get all until end of content
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
the code return a given bulk in yahoo and json format
so remove the unknown format which is
"/**/YAHOO.Finance.CurrencyConverter.addConversionRates (" and ends with ");"
by
$contents = str_replace('/**/YAHOO.Finance.CurrencyConverter.addConversionRates(','',$contents);
$contents = str_replace(');','',$contents);
$obj = json_decode($contents,true);
then loop the content by
foreach($obj['list']['resources'] as $key0 => $value0){
}
I prefer to use file_get_contents to get the html and preg_match_all to cleanup the json, i.e.:
<?php
$json = file_get_contents("http://finance.yahoo.com/connection/currency-converter-cache?date=20140113");
preg_match_all('/\((.*)\);/si', $json, $json, PREG_PATTERN_ORDER);
$json = $json[1][0];
$json = json_decode($json,true);
foreach ($json["list"]["resources"] as $resource){
echo $resource["resource"]["fields"]["date"];
echo $resource["resource"]["fields"]["price"];
echo $resource["resource"]["fields"]["symbol"];
echo $resource["resource"]["fields"]["price"];
}
NOTE:
I've tested the code and it works as intended.

Modify text file with php code

I have a JSON file badly formatted (doc1.json):
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192}
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472}
{...}{...}
And I have to change it in this:
{"u":[
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192},
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472},
{...},{...}
]}
Can I do this in a PHP file?
//Get the contents of file
$fileStr = file_get_contents(filelocation);
//Make proper json
$fileStr = str_replace('}{', '},{', $fileStr);
//Create new json
$fileStr = '{"u":[' . $fileStr . ']}';
//Insert the new string into the file
file_put_contents(filelocation, $fileStr);
I would build the data structure you want from the file:
$file_path = '/path/to/file';
$array_from_file = file($file_path);
// set up object container
$obj = new StdClass;
$obj->u = array();
// iterate through lines from file
// load data into object container
foreach($array_from_file as $json) {
$line_obj = json_decode($json);
if(is_null($line_obj)) {
throw new Exception('We have some bad JSON here.');
} else {
$obj->u[] = $line_obj;
}
}
// encode to JSON
$json = json_encode($obj);
// overwrite existing file
// use 'w' mode to truncate file and open for writing
$fh = fopen($file_path, 'w');
// write JSON to file
$bytes_written = fwrite($fh, $json);
fclose($fh);
This assumes each of the JSON object repsentations in your original file are on a separate line.
I prefer this approach over string manipulation, as you can then have built in checks where you are decoding JSON to see if the input is valid JSON format that can be de-serialized. If the script operates successfully, this guarantees that your output will be able to be de-serialized by the caller to the script.

How can I get some text from data uri and assign to an array?

my data
this1
this2
this3
this4
what I want
$keepit[0]='this1';
$keepit[1]='this2';
$keepit[2]='this3';
$keepit[3]='this4';
data uri
data:text/plain;charset=utf-8;base64,dGhpczENCnRoaXMyDQp0aGlzMw0KdGhpczQ=
Is it possible to do this?
You can do this with normal file methods using the data:// protocol:
$data = file('data://text/plain;charset=utf-8;base64,dGhpczENCnRoaXMyDQp0aGlzMw0KdGhpczQ=');
Alternatively though you can pull out the base64 encoded string and decode it yourself:
$plaintext = base64_decode('dGhpczENCnRoaXMyDQp0aGlzMw0KdGhpczQ=');
If the encoded string can be decoded this will work:
$file_path = ''; // change this.
$fp = fopen($file_path, 'rb');
$contents = fread($handle, filesize($file_path));
fclose($fp);
$data_uri = preg_split('/,/', $contents);
$encoded = $data_uri[1];
$decoded = base64_decode($encoded);
var_dump($decoded);

Categories