I am trying to send JSON information from Python to PHP through a JSON file data.json, based on the content of the Stack Overflow question/answer here. I am running this code all on an Apache web server on Raspberry Pi 3.
Here is my code:
Python
import sys, json, random # I know I don't need sys and random to run this, but I was using these in my previous code.
data = {'fruit':['oranges', 'apples', 'peaches'], 'age':12}
with open('data.json', 'w') as outfile:
json.dump(data, outfile)
When run, this program worked fine and exited with code 0.
JSON file
{"age": 12, "fruit": ["oranges", "apples", "peaches"]}
As you can see, my Python worked perfectly and the output is identical to the data variable in my python code. On second thought, the order is backward, although I don't think this matters.
PHP
Now, this is where the problem is:
<?php
$string = file_get_contents("data.json");
$json_a = json_decode($string, true);
$arr = array();
foreach ($json_a as $key) {
array_push($arr,json_decode($key[0],true));
}
echo json_encode($arr);
?>
When run, the program exited with code 0 but outputed:
[null,null]
Does anyone have an idea why this is, or is this just the way JSON works?
The original code with issues:
<?php
$string = file_get_contents("data.json");
$json_a = json_decode($string, true);
$arr = array();
foreach ($json_a as $key) {
// No need to use json_decode again
// as it is already converted to an array
// by the inital json decode statement
array_push($arr,json_decode($key[0],true));
}
echo json_encode($arr);
?>
Pretty printed PHP Array which is stored inside $json_a:
Array
(
[age] => 12
[fruit] => Array
(
[0] => oranges
[1] => apples
[2] => peaches
)
)
The problem:
In the original script, json_decode was used on an already decoded variable/array which returned nothing and hence null was appended to your list.
Code walkthrough:
During the first iteration of the foreach loop,
$key will have the value 12 - which is a string
During the second iteration of the foreach loop,
$key will have the value - which is an Array
Array
(
[0] => oranges
[1] => apples
[2] => peaches
)
The corrected code for printing all the fruits:
<?php
$string = file_get_contents("data.json");
$json_a = json_decode($string, true);
$arr = array();
foreach ($json_a['fruit'] as $key) {
array_push($arr,$key);
}
echo json_encode($arr);
?>
The above snippet returns ["oranges","apples","peaches"]
Related
I have one text file in directory. I want to get contents of that text file.
in my text file
student&class&mark&grade
I am trying to my code here.
$myfile = "data.txt" ;
$getdata = file($myfile) ;
print_r($getdata) ; // student&class&mark&grade // working fine.
I'm trying to explode function
$arr = explode('&',$getdata);
print_r($arr); // not working
how to solve this problem ?
file() function return the data in array - file function
file_get_contents() return the data in string form
Try file_get_contents() - file_get_contents
$myfile = "data.txt" ;
$getdata = file_get_contents($myfile) ;
$arr = explode('&',$getdata);
print_r($arr); // Will work
file() returns an array of the lines of the file, so this is the main problem. You will also find that file() will, by default, include a new line on the end of each line - which you probably don't want.
This code uses array_walk() to process each line, using explode() on a line at a time, replacing the original line with the array.
$getdata = file($myfile, FILE_IGNORE_NEW_LINES);
array_walk ( $getdata, function ( &$data ) { $data = explode("&", $data);});
print_r($getdata);
This outputs...
Array
(
[0] => Array
(
[0] => student
[1] => class
[2] => mark
[3] => grade
)
)
My String is
["Alchemy","Alchemy-w","Alchemy-b"]
How can I made it to like
Array (
[0] => Alchemy
[1] => Alchemy-w
[2] => Alchemy-b
}
Please help me, How I Can get this output in a Stranded manner else I have to cut it using sub-string or any other ordinary php functions.
the string is a valid json-string. so you could use json_decode:
$json = '["Alchemy","Alchemy-w","Alchemy-b"]';
var_dump(json_decode($json));
Your string is json. just do this:
<?php
$json = '["Alchemy","Alchemy-w","Alchemy-b"]';
$array = json_decode($json, true); //When TRUE, returned objects will be converted into associative arrays.
echo "<pre>"; //to get it displayed nicely
print_r($array);
?>
Your string is json format only, you can use following mathod.
$resp = '["Alchemy","Alchemy-w","Alchemy-b"]';
print_r(json_decode($resp));
so I have this variable $_GET which receives the value such as
set=QnVzaW5lc3M=|RmluYW5jZQ==
The values are base64 enconded using base64_encode() and then separated by a delimiter '|'. I'm using implode function to generate the value of the set variable.
Now, the question is, how can I get the values from the set variable into an array and base64 decode them as well ?
Any suggestions are welcome.
I tried this :-
$test = array();
$test = explode('|', $_GET['set']);
var_dump($test);
This throws the value which is not usable.
But this made no difference.
$data = 'QnVzaW5lc3M=|RmluYW5jZQ==';
$result = array_map(
'base64_decode',
explode('|', $data)
);
var_dump($result);
This should work using foreach:
// Set the test data.
$test_data = 'QnVzaW5lc3M=|RmluYW5jZQ==';
// Explode the test data into an array.
$test_array = explode('|', $test_data);
// Roll through the test array & set final values.
$final_values = array();
foreach ($test_array as $test_value) {
$final_values[] = base64_decode($test_value);
}
// Dump the output for debugging.
echo '<pre>';
print_r($final_values);
echo '</pre>';
The output is this:
Array
(
[0] => Business
[1] => Finance
)
I have a Python script running on my server that creates a 2D list like so:
[['Header1', 'Header2', 'Header3'], ['2012-09-10 00:11:00', '61.3', '57.0'], ...]
I pass this back to the PHP script which is running my webpage. Here's the PHP I'm currently using to get the array. I get the rows, but obviously with an unwanted [[ at the start and ]] at the end.
exec("python weatherdata.py $stationID $startdate $enddate", $pyoutput);
$vars = explode("], [", $pyoutput[0]);
For the sake of explaining what I actually want to do, since there's bound to be a "proper" solution (I'm not at all familiar with PHP), what I want to do is adapt the code from here which download a CSV file to the user, but uses mySQL to populate it. The set-up part here works fine.
Edited in response to Jack's answer below
// Commented out my working parsing part
// remove the start and end square braces then split into rows
//$output = str_replace("[[","",$pyoutput);
//$output = str_replace("]]","",$output);
//$rows = explode("], [", $output[0]);
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
foreach (preg_split('/],\s*\[/', trim($pyoutput, '[]')) as $row) {
$data= preg_split("/',\s*'/", trim($row, "'"));
fputcsv($data);
}
// Commented out my working write to CSV part
// write rows
//foreach ($rows as $row){
// $row = str_replace("'","",$row);
// $row = explode(",", $row);
// fputcsv($output, $row);
//}
Not sure whether this is viable for you, but since PHP 5.4 it supports the short array syntax, e.g. [1, 2, 3] instead of array(1, 2, 3).
So, you could just use evil ... I mean eval():
$vars = eval(`python weatherdata.py $stationID $startdate $enddate`);
Otherwise, if the array syntax is always in that format, just break it apart with preg_split(), first on square brackets and then on single quotes:
foreach (preg_split('/],\s*\[/', trim($s, '[]')) as $row) {
$data = preg_split("/',\s*'/", trim($row, "'"));
print_r($data);
}
Output:
Array
(
[0] => Header1
[1] => Header2
[2] => Header3
)
Array
(
[0] => 2012-09-10 00:11:00
[1] => 61.3
[2] => 57.0
)
This question already has answers here:
How create an array from the output of an array printed with print_r?
(11 answers)
Closed 10 years ago.
How can i create variable from it's print_r output ? In other words, i'd like to know if something similar to my fictive var_import function exists in php ? var_import would be the inverse of var_export
He is a use case:
$a = var_import('Array ( [0] => foo [1] => bar )');
$output = var_export($a);
echo $output; // Array ( [0] => foo [1] => bar )
If such a function does not exist, is there a tool (or online tool) to do this ?
I am also interested to do the same with var_dump output.
EDIT: The variable is only available as a print_r output (string). To clarify what i need, imagine the folowing situation: someone posts a some sample on the internet somewhere with a print_r output. To test his code, you need to import his print_r variable into your code. This is an example where var_import would be usefull.
Amusingly the PHP manual contains an example that tries to recreate the original structure from the print_r output:
print_r_reverse()
http://www.php.net/manual/en/function.print-r.php#93529
However it does depend on whitespace being preserved. So you would need the actual HTML content, not the rendered text to pipe it back in.
Also it doesn't look like it could understand anything but arrays, and does not descend. That would be incredibly difficult as there is no real termination marker for strings, which can both contain newlines and ) or even [0] and => which could be mistaken for print_r delimiters. Correctly reparsing the print_r structure would be near impossible even with a recursive regex (and an actual parser) - it could only be accomplished by guesswork splitting like in the code linked above.. (There are two more versions there, maybe you have to try them through to find a match for your specific case.)
Why don't you use var_export instead ?
var_export(array(1, 2, 3)); // array(1, 2, 3)
You can import var_export's output with eval(), however I would recommend you to avoid this function as much as possible.
The following functions are better for exporting and importing variables:
serialize() and unserialize():
$string = serialize(array(1, 2, 3));
$array = unserialize($string); // array(1, 2, 3);
Or json_encode() and json_decode():
$string = json_encode(array(1, 2, 3));
$array = json_decode($string);
You can wrap it in an output buffer:
ob_start();
print_r(array(1,2,3));
$arr = ob_get_clean();
echo $arr;
Ok so I misunderstood the first question. I think I have another solution which actually does answer your question:
<?php
$ar = array('foo','bar');
$p = print_r($ar, true);
$reg = '/\[([0-9]+)\] \=\> ([a-z]+)/';
$m = preg_match_all($reg, $p, $ms);
$new_ar = $ms[2];
echo "Your wanted result:\n";
print_r($new_ar);
If you want to import a var_export()'s variable, you can run the eval() function.
Or if you save the contents into a file (with a return statement), you can use the return value of include() or require().
But I would rather use serialize() and unserialize() or json_encode() and json_decode().
define('EXPORT_JSON', 1);
define('EXPORT_SERIALIZE', 2);
function exportIntoFile($var, $filename, $method=EXPORT_JSON)
{
if ( $method & EXPORT_JSON )
file_put_contents( $filename, json_encode($var) );
else if ($method & EXPORT_SERIALIZE)
file_put_contents( $filename, serialize($var) );
}
function importFromFile($filename, $method=EXPORT_JSON)
{
if ( $method & EXPORT_JSON )
return json_decode( file_get_contents($filename) );
else if ($method & EXPORT_SERIALIZE)
return unserialize( file_get_contents($filename) );
}
I'm not good at regex to code the final trash removal. Here is how far I could get though:
$str = 'Array ( [0] => foo [1] => bar [2] => baz)';
$t1 = explode('(', $str);
$t2 = explode(')', $t1[1]);
$t3 = explode(' => ', $t2[0]);
unset($t3[0]);
print_r($t3);
output:
Array
(
[1] => foo [1]
[2] => bar [2]
[3] => baz
)