how to retrieve array value using php - php

I want to retrieve array value.
This is my array value:
overlay.txt:
{"title":"sss","description":"sss","code":"sss"}
{"title":"trtr","description":"trtr","code":"tyrytr"}
{"title":"ret54","description":"56tr","code":"ty76"}
{"title":"rgfdg","description":"dfgdfg","code":"dfgdfg"}
{"title":"asfafdsf","description":"sdfsdf","code":"sdfsdfsdf"}
This is my code: but this is not working.why?
How to retrieve value from overlay.txt file.
I did not get all title value.
I do not known how to get title value from overlay.txt
The $title is showing empty.
Where I want to change in my code to get $title value.
$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
$fd = fopen($file, "a"); // a for append, append text to file
fwrite($fd, $json);
fclose($fd);
$filecon = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays',$filecon);
//overlays page;
foreach($filecon as $files)
{
$title=$files['title'];
echo $title;
}

You're encoding your array to JSON, so at some point you need to decode it again into a PHP array. Since you actually have several JSON objects in the file, you need to decode each one individually. Assuming it's always one JSON object per line, this'll do:
$jsonObjects = file('overlay.txt', FILE_IGNORE_NEW_LINES);
foreach ($jsonObjects as $json) {
$array = json_decode($json, true);
echo $array['title'];
...
}
This will very quickly break if there are line breaks within the serialized JSON, e.g.:
{"title":"ret54","description":"foo
bar","code":"ty76"}
That way of storing the data is not very reliable.

make overlay.txt fully json format:
[
{"title":"sss","description":"sss","code":"sss"},
{"title":"trtr","description":"trtr","code":"tyrytr"},
...
]
and try this:
$raw = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays', array("filecon" => json_decode($raw)));
overlay page:
<?php
foreach($filecon as $files) {
echo $files['title'];
}
?>
If you want to use $filecon in view file,
set an array which has the key "filecon" in $this->load->view()'s second argument.
http://codeigniter.com/user_guide/general/views.html

Related

Adding object to array also adds 'null'

I send the following data to my php file via ajax:
JSON.stringify({test1: '1', test2: '2'})
I would like to write this data to my JSON FILE content.json containing an empty array
[]
I only want to add the content though if it is not there, yet. This is my PHP code:
$jsonStringObject = file_get_contents("php://input");
$phpObject = json_decode($jsonStringObject);
$newJsonStringObject = json_encode($phpObject);
header('Content-Type: application/json');
$jsonString = file_get_contents('content.json');
$data = (array) json_decode($jsonString, true);
if (in_array($phpObject, $data) === false){
$data[] = $phpObject;
}
$newJsonString = json_encode($data);
file_put_contents('content.json', $newJsonString);
It almost works. Something is wrong with the way the data is added to the array because when I call the function for the first time, it updates content.json to
[null,{"test1":"1","test2":"2"}]
On calling the function again, it adds the object again despite the if-statement:
[null,{"test1":"1","test2":"2"},{"test1":"1","test2":"2"},{"test1":"1","test2":"2"}]
Can anyone help me to spot the mistake?
You're comparing apples and oranges (or rather objects to arrays).
Make sure you decode all json as arrays:
$jsonStringObject = file_get_contents("php://input");
// Added true as second argument to get it bas as an array
$phpObject = json_decode($jsonStringObject, true);
$jsonString = file_get_contents('content.json');
// Removed the (array) since the second argument literally means "return as array"
$data = json_decode($jsonString, true);
if (in_array($phpObject, $data) === false){
$data[] = $phpObject;
}
$newJsonString = json_encode($data);
file_put_contents('content.json', $newJsonString);
Demo: https://3v4l.org/rnCn5

.JSON file creates NULL value via PHP

So I'm trying to figure out why I get a NULL value in my .json file after I try to write the array to it. It only happens with the 'array_push' line after creating a new file. If there is a .json file already there with a value in it, it'll write to it correctly. The only thing I could guess was the file is missing the '{' and '}' in it upon creation.
I've got a small work around so far, but not sure that this is the right way to do it. Can someone tell me if this is good or bad?
Just to clarify, the .json document only holds the vault of NULL, there are no array elements or anything in the file besides the word NULL.
//CHECK IF FILE EXISTS, ELSE CREATE IT
$log_filename = "./site_files/logs/error-404-log.json";
if(!file_exists($log_filename)) {
touch($log_filename);
//LINE BELOW IS MY WORK AROUND, I'M NOT SURE IF THIS IS THE RIGHT WAY
file_put_contents($log_filename, json_encode(json_decode("{}")));
echo "$log_filename was created. <br />";
}
$log_array = array();
$new_data = array(
'current_date_stamp' => $current_date_stamp,
'current_page_trail' => $current_page_trail
);
$json_data = file_get_contents($log_filename);
if($log_array != "") { $log_array = json_decode($json_data, true); }
//WHEN CREATING A NEW FILE, ARRAY_PUSH GIVES ERROR
array_push($log_array, $new_data);
$json_data = json_encode($log_array, JSON_PRETTY_PRINT);
file_put_contents($log_filename, $json_data);
$log_filename = "error-404-log.json"; // establish the path/to/filename.json
if (file_exists($log_filename)) { // if path/to/filename.json exists
$json = file_get_contents($log_filename); // access PRETTY json string
echo "pre-existing data: <div><pre>$json</pre></div><br>"; // display json string
$array = json_decode($json, true); // decode to prepare for new data
}
// data always maintains the same structure: an array of 2-element arrays
$array[] = [
'current_date_stamp' => date('Y-m-d H:i:s'),
'current_page_trail' => "foo"
];
// create/update the file
$new_json = json_encode($array, JSON_PRETTY_PRINT); // re-encode updated array data
echo "new data: <div><pre>$new_json</pre></div>"; // display new json string
file_put_contents($log_filename, $new_json); // create or overwrite file
Your code is failing because you are comparing $log_array with an empty string, this condition will always pass because this array will never be an empty string. In the if statement you decode the contents of the file, when the file has no content this will be an empty string and it will return NULL, after this you write this NULL value to your file. If you check if $json_data is an empty string your code should work, I would also recommend doing it like this:
$log_array = array();
$new_data = array(
'current_date_stamp' => $current_date_stamp,
'current_page_trail' => $current_page_trail
);
$json_data = file_get_contents($log_filename);
if($json_data != "") {
$log_array = json_decode($json_data, true);
//WHEN CREATING A NEW FILE, ARRAY_PUSH GIVES ERROR
array_push($log_array, $new_data);
$json_data = json_encode($log_array, JSON_PRETTY_PRINT);
file_put_contents($log_filename, $json_data);
}
This is better since if the string is empty all other actions are irrelevant.

Json api decoding

here is my json
{
"rgInventory": {
"5455029633": {
"id":"5455029633",
"classid":"310776543",
"instanceid":"302028390",
"amount":"1"
}
}
}
Here is my way to parse json in php
$content = file_get_contents("http://steamcommunity.com/profiles/76561198201055225/inventory/json/730/2");
$decode = json_decode($content);
foreach($decode->rgInventory->5455029633 as $appid){
echo $appid->id;
}
I need to get that 5455029633 but it dont work in foreach.
And I want to store it in the variable too.
Json, which you've provided is invalid. Remove last comma from "amount":"1", and you are missing closing curly bracket. Then you should be able to access desired value as $decode->rgInventory->{"5455029633"}.
Or make your life simpler ;) and just go for assoc array $decode = json_decode($content, true);
You will need to pass true as second argument to the function json_decode to get an array instead of an object :
PHP
<?php
$content = file_get_contents("http://steamcommunity.com/profiles/76561198201055225/inventory/json/730/2");
$decode = json_decode($content, true);
echo $decode['rgInventory']['6255037137']['id']; // will output the property 'id' of the inventory 6255037137
$invetory = $decode['rgInventory']['6255037137'] // will store the inventory 6255037137 in the variable $inventory
?>

Decode JSON to PHP

I have a .txt file called 'test.txt' that is a JSON array like this:
[{"email":"chrono#gmail.com","createdate":"2016-03-23","source":"email"}]
I'm trying to use PHP to decode this JSON array so I can send my information over to my e-mail database for capture. I've created a PHP file with this code:
<?php
$url = 'http://www.test.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
echo $json;
?>
For some reason, it's not echoing the decoded JSON when I visit my php page. Is there a reason for this and can anyone shed some light? Thanks!
You use echo to print scalar variables like
$x = 'Fred';
echo $x;
To print an array or object you use print_r() or var_dump()
$array = [1,2,3,4];
print_r($array);
As json_decode() takes a JSON string and converts it to a PHP array or object use print_r() for example.
Also if the json_decode() fails for any reason there is a function provided to print the error message.
<?php
$url = 'http://www.test.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
if ( json_last_error() !== JSON_ERROR_NONE ) {
echo json_last_error_msg();
exit;
}
You'll need to split that json string into two separate json strings (judging by the pastebin you've provided). Look for "][", break there, and try with any of the parts you end up with:
$tmp = explode('][', $json_string);
if (!count($tmp)) {
$json = json_decode($json_string);
var_dump($json);
} else {
foreach ($tmp as $json_part) {
$json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');
var_dump($json);
}
}

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);

Categories