Change a value of json variable in a php file - php

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

May be it is that you want
$json_variable = json_decode('{"pen_color":"red","book_size":"large","book_color":"red"}', true);
$json_variable['pen_color'] = 'green';
$json_value = json_encode($json_variable);
file_put_contents('my-file.php', $json_value );

Related

How to Change Variable Value on new line in Php

Here i have single line of variable value. You can see here below in php source code
<?php
$list = "03343922581 03136011388 03142181356 03471819024 03003973577";
//Please tell me the php code
?>
I want to get output like below
03343922581
03136011388
03142181356
03471819024
03003973577
for show result in html page according to your desire you can use :
$new_list = str_replace(" ","\n",$list);
echo nl2br($new_list);

PHP function to call JSON files

I am trying to make a basic PHP function in order to call json files repeatedly throughout the app. Every time I want to call a json file I use:
<? $site = json_decode(file_get_contents('views/partials/site.json')); ?>
Then I use echo to use data from json file like this:
<? echo $site[0]->title; ?>
But instead of repeating part one I want to write a function in the header and call it where I want to call a json file. After that i was planning to use the function like this:
$site = jsonCall('site');
by using the function below;
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
echo $jsonCalled;
};
but instead of what i want i got an array as a response from server. i think my function turns json file to an array and that way i can't call it properly.
anyone knows how to solve this simple issue? show me proper way to write this function so my code might look a bit easier to read. Thank you.
by changing echo in function with return and using jsonCall('site')[0]->title; everything worked fine.
Of course you are getting an array. Otherwise $site[0] (which is an array access at key zero) would not have worked.
From the PHP docs (http://php.net/manual/en/function.json-decode.php):
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
Your appropriate PHP type is array.
The following should work:
jsonCall('site')[0]->title;
Therefore I can not see a problem with your code?
The server is responding with Array because that is how PHP represents an array when you are echo'ing it. Your function should be returning the result.
Try:
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
// echo $jsonCalled;
return $jsonCalled; // <- this should work
};

Trying to grab value from html page but getting template back not the value - php

I am making a price crawler for a project but am running into a bit of an issue. I am using the below code to extract values from an html page:
$content = file_get_contents($_POST['url']);
$resultsArray = array();
$sqlresult = array();
$priceElement = explode( '<div>value I want to extract</div>' , $content );
Now when I use this to get certain elements I only get back
Finance: {{value * value2}}
I want to get the actual value that would be displayed on the screen e.g
Finance: 7.96
The other php methods I have tried are:
curl
file_get_html(using simple_html_dom library)
None of these work either :( Any ideas what I can do?
You just set the <div>value I want to extract</div> as a delimiter, which means PHP looks for it to separate your string to array whenever this occurs.
In the following code we use , character as a delimiter:
<?php
$string = "apple,banana,lemon";
$array = explode(',', $string);
echo $array[1];
?>
The output should be this:
banana
In your example you set the value you want to extract as a delimiter. That's why this happens to you. You'll need to set a delimiter between your string you want to obtain and other string you won't need at the moment.
For example:
<?php
$string = "iDontNeedThis-dontExtractNow-value I want to extract-dontNeedEither";
$priceElement = explode('-', $string);
echo "<div>".$priceElement[2]."</div>";
?>
The code should output this to your HTML page:
<div>value I want to extract</div>
And it will appear on your page like this:
value I want to extract
If you don't need to save the whole array in a variable, you can save the one index of it to variable instead:
$priceElement = explode('-', $string)[2];
echo $priceElement;
This will save only value I want to extract so you won't have to deal with arrays later on.

Get some value from url?

I have this kind of url from youtube, with the value of video
$url='http://www.youtube.com/watch?v=H_IkPia6eBA&';
What i need is just to get new string with value of V etc in this case
$newstring='H_IkPia6eBA&';
I dont know how long V could be, only i need to get that value of V, I have tried
$string = 'http://www.youtube.com/watch?v=oYyslNuRcwM';
$url = parse_url($string);
parse_str($url['query'], $query);
print_r($query);
Tried with this, but in CodeIgniter post, I only get empty array?
You're almost there already.
<?php
$string = 'http://www.youtube.com/watch?v=oYyslNuRcwM';
$url = parse_url($string);
parse_str($url['query'], $query);
$newstring=$query["v"]; // just this line is missing
echo $newstring;
?>
Demo
But you know something? If the url format is always going to be like that then no need for all those functions. It then can simply be
<?php
$url='http://www.youtube.com/watch?v=H_IkPia6eBA&';
echo str_replace("http://www.youtube.com/watch?v=","",$url);
?>

json_decode returning an array of 1

I am trying to decode some JSON into a php array. Here's the code excerpt:
$getfile="{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}";
$arr = json_decode($getfile, true);
$arr['day3'] = $selecter;
echo(print_r($arr));
The only thing that gets returned is '1'. I've checked JSONLint and it is valid json, so I'm wondering why json_decode is failing. I also tried checking what the array is before adding the day3 key to it, and I still return a '1'. Any help is appreciated!
Actual code:
$getfile = "";
$getfile = file_get_contents($file);
if ($getfile == "") {
writeLog("Error reading file.");
}
writeLog("getfile is " . $getfile);
writeLog("Decoding JSON data");
$arr = json_decode($getfile, true);
writeLog("Decoded raw: " . print_r($arr));
writeLog("Editing raw data. Adding data for day " . $day);
$arr['day3'] = $selecter;
writeLog(print_r($arr));
$newfile = json_enconde($arr);
writeLog($newfile);
if (file_put_contents($file, $newfile)) {
writeLog("Wrote file to " . $file);
echo $newfile;
} else {
writeLog("Error writting file");
}
These are the contents of $file (it's a text file)
{"fname":"Bob","lname":"Thomas","cascade":"bthomas","loc":"res","place":"home 2"}
We still don't know what's in your file. However if:
"{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}"
Then the extraneous outer double quotes will screw the JSON, and json_decode will return NULL. Use json_last_error() to find out. Might also be a UTF-8 BOM or something else ...
Anyway, the 1 is the result from print_r. print_r outputs directly, you don't need the echo. Also for debugging rather use var_dump()
More specifically you would want the print_r output returned (instead of the boolean success result 1) and then write that to the log.
So use:
writeLog(print_r($arr, TRUE));
Notice the TRUE parameter.
First, use a single quote. That will cause a parse error
$getfile= '{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}';
I assume you have already declared $selecter and it has been assigned to some value.
Remove echo from echo(print_r($arr)) You don't need echo. print_r will also output. If you use echo, it will display 1 at the end of array.
The working code:
$getfile = '{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}';
$arr = json_decode($getfile, true);
$selecter = 'foobar';
$arr['day3'] = $selecter;
print_r($arr);
Hope this helps.
I had this problem when doing it like this:
if ($arr = json_decode($getfile, true)) {
$arr['day3'] = $selecter;
echo(print_r($arr));
}
Decoding it outside of if was the solution.

Categories