John Davidson

Change a value of json variable in a php file

0 comments
Message:


Hi i have a php file that contain json value. I want to change the value of json variable .But i am not sure how t do that .


my-file.php


<?
$json_data;
$json_varible = json_decode('{"pen_color":"red","book_size":"large","book_color":"red", etc etc }', true);
....
?>

Now I want to change the value of pen_color to green . Please note there are many parameters in json_decode


So i write following


//read the entire string
$str=file_get_contents('my-file.php');
$old_value= "red";
$new_value = "green";

//replace something in the file string - this is a VERY simple example
$str=str_replace($old_value, $new_value,$str);

file_put_contents('my-file.php', $str);

I am sure that this code is wrong. Please help me to solve the issue. I want t change pen_color to green



My Answer:
You are on the right track, but you need to modify your approach slightly. Since the JSON data is stored in a variable in your PHP file, you can decode it, update the value of the "pen_color" key, and then encode it back to JSON before saving it back to the file. Here's how you can do it:

php
// Read the entire PHP file
$str = file_get_contents('my-file.php');

// Extract the JSON data from the file
$pattern = '/\$json_varible = json_decode\(\'(.*?)\', true\);/s';
preg_match($pattern, $str, $matches);
$json_data = $matches[1];

// Decode the JSON data
$json_array = json_decode($json_data, true);

// Update the value of the "pen_color" key
$json_array['pen_color'] = 'green';

// Encode the updated JSON data
$new_json_data = json_encode($json_array, JSON_PRETTY_PRINT);

// Replace the old JSON data with the updated JSON data in the file string
$new_str = str_replace($json_data, $new_json_data, $str);

// Save the modified PHP file
file_put_contents('my-file.php', $new_str);
?>


This code will extract the JSON data from the PHP file, update the value of the "pen_color" key to "green", and then save the modified JSON data back to the file. Make sure to replace 'my-file.php' with the actual path to your PHP file.

Rate this post

5 of 5 based on 4086 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us