I have a PHP file that runs a Perl script, using popen and the perl script outputs the following back to the php
{ 'City' => [ 'LA', 'Chicago', 'NY' ], 'Name' => 'Kevin Bridges', 'Id' => '7075', 'Last-Status-Change' => { 'Time' => 14172911, 'User' => 'kbridge', 'To' => 'LAX', 'From' => 'ORD' }}
I cannot modify the perl script, and I really don't know the contents of it. But it looks like it is outputting JSON. I have tried using json_encode to grab the contents of the output but no success. Can anyone tell me if it is possible to parse this or do I have to manually write a parser?
Convert => to : and ' to ". After that use json_decode to create associative array from the string.
$array = json_decode(str_replace(["=>", "'"], [":", '"'], $a), true);
That's not JSON but is "almost" the PHP [] array syntax, except it uses some {}. You could try:
eval('$array = ' . str_replace(['{','}'], ['[',']'], $output) . ';');
print_r($array);
It does not looks like to be a valid JSON, it seems to be a PERL hash, so i think you gonna need to parse that manually... a simple way to you accomplish that in PHP, it would be to replace the {-} to [] and you can eval that string to be consider an array in PHP
Related
For example, a PHP file contains this:
<?php
return [
'sample_array' => [
'sample_index' => 'sample_data',
],
];
I would like to append values to sample_array using a PHP script. What would be the best way to do this?
Edit:
After running the script, file should be updated to:
<?php
return [
'sample_array' => [
'sample_index' => 'sample_data',
'sample_index2' => 'sample_data2',
],
];
Edit:
What I'm looking for is the creation of a script that will directly update the contents of the PHP file to append the array.
You can create valid PHP code through the use of var_export(). You can then store the code in a file with something like file_put_contents().
// load the array from the file
$arr = include 'file.php';
// modify the array
$arr['sample_array']['sample_index2'] = 'sample data 2';
// write it back to the file
file_put_contents("file.php", "return " . var_export($arr, true) . ";");
gives you...
return array (
'sample_array' =>
array (
'sample_index' => 'sample_data',
'sample_index2' => 'sample data 2',
),
);
I think you might be after array_push
<?php
$sample_array = [
'sample_index' => 'sample_data',
];
array_push($sample_array, array(
'sample_index2' => 'sample_data2',
));
return $sample_array;
With array push, the second argument could be another array that you have already defined with multiple values and keys
More info at php.net array_push
Hey I am trying to pass data back in json format using json_encode.
However it seems to return like this:
[{‘county’:’us’,’sector’:’retail’}]
However the end user has said that they expect the response without the square brackets.
How do I do this?
Thanks.
Depends on how you are generating the value you encode... json_encode has an option JSON_FORCE_OBJECT you could use but from what I can see that's probably not what you want, as it seems to me this would only turn the "square brackets" into a wrapper object. Nevertheless, if you'd like to try:
json_encode($value, JSON_FORCE_OBJECT);
Edit: as others have said, it seems likely json_encode($value[0]) is what you want.
Assuming your array is:
$data = [
'country' => 'us',
'sector' => 'retail',
];
Then just return a json_encoded array like so:
json_encode($data);
// {"country":"us","sector":"retail"}
However, if your array with data is "nested" like so:
$data = [[
'country' => 'us',
'sector' => 'retail',
]];
then return the encoded first element of it:
json_encode($data[0]);
// {"country":"us","sector":"retail"}
My experience of this happening is that you're accidentally storing your data as the first item of an array.
For example you may have done:
$json_store = Array();
$json_store[] = Array('country' => 'us', 'sector' => 'retail');
$json = json_encode($json_store);
A way of testing for this is to see if doing the following removes the brackets:
$json_encode($json_store[0])
If it does, you've a unnecessarily nested array that you should fix. Using the above line probably should be avoided as it's better to fix how the data is stored in the first place.
I created a REST API using Laravel (Lumen). Basically I'm taking some values from database and need to do some functions. Here's the problem.
There's a field called web_data in my result set. It's Perl code. This is how it looks when I query the database using normal SQL editor like phpmyadmin and workbench.
{"caption" => "Genes (Comprehensive set from GENCODE 26)","colour_key" => "[biotype]","default" => {"MultiBottom" => "collapsed_label","MultiTop" => "gene_label","alignsliceviewbottom" => "as_collapsed_label","contigviewbottom" => "transcript_label","contigviewtop" => "gene_label","cytoview" => "gene_label"},"key" => "ensembl","label_key" => "[biotype]","multi_name" => "GENCODE 26 Comprehensive gene set","name" => "Comprehensive Gene Annotations from GENCODE 26"}
It's very clear and nothing wrong. But when I get the same result via my REST API, I'm getting the following output. It has many "\" symbols. Here's that output.
{\"caption\" => \"Genes (Comprehensive set from GENCODE 26)\",\"colour_key\" => \"[biotype]\",\"default\" => {\"MultiBottom\" => \"collapsed_label\",\"MultiTop\" => \"gene_label\",\"alignsliceviewbottom\" => \"as_collapsed_label\",\"contigviewbottom\" => \"transcript_label\",\"contigviewtop\" => \"gene_label\",\"cytoview\" => \"gene_label\"},\"key\" => \"ensembl\",\"label_key\" => \"[biotype]\",\"multi_name\" => \"GENCODE 26 Comprehensive gene set\",\"name\" => \"Comprehensive Gene Annotations from GENCODE 26\"}
Can you please tell me what's the reason for this? Is this an issue with PHP or something like that ?
And also I have another issue. This is Perl code containing "=>" symbols to seperate values. I need to convert this into a JSON object using PHP. Is that possible ?
Need to convert like following object.
{ "caption" : "Genes (Comprehensive set from GENCODE 26)", "colour_key" : "[biotype]", "default" : { "MultiBottom" : "collapsed_label" ...
This is the php code i'm using to create the REST output using SQL data.
public function testDualDatabaseConnection()
{
$testGene = DB::connection('mysql2')->select('select a.analysis_id, logic_name, ad.description, ad.display_label, ad.web_data FROM ( select distinct(analysis_id) as analysis_id from gene ) as a join analysis on (a.analysis_id = analysis.analysis_id) join analysis_description as ad on (analysis.analysis_id = ad.analysis_id) where ad.displayable = :wow1', ['wow1' => "1"]);
return response()->json($testGene);
}
And also this is the full JSON output i'm getting via REST API.
https://gist.github.com/chanakaDe/0d1e5916d8bc788bb101afa9b92dc9cd
In this response, you can see "web_data", that's also the part I need to convert to JSON again.
If on the off chance you really do have
{\"caption\" => \"Genes ...\", ...}
Then you have a JSON fragment, and the first you thing you need to do is turn it into a complete JSON document so it can be decoded.
$json_fragment_from_api = '{\"caption\" => \"Genes ...\", ...}';
$json_from_api = '{"result":"' . $json_fragment_from_api . '"}';
$response = json_decode($json_from_api, true);
$perl_code = $response["result"];
That said, I think it's far more likely that you only showed a portion of your actual input. You're far more likely to have received something that looks more like
{ "result": "{\"caption\" => \"Genes ...\", ...}" }
Since you already have a complete JSON document, simply start by decoding it.
$json_from_api = '{ "result": "{\"caption\" => \"Genes ...\", ...}" }';
$response = json_decode($json_from_api, true);
$perl_code = $response["result"];
At this point, you have the value from the database.
{"caption" => "Genes ...", ...}
That value is Perl code. More specifically, it's surely Perl code that was produced by Data::Dumper. This is going to be hard to convert into JSON.
You could use the following, but it won't handle everything:
$desired_json = str_replace(' =>', ':', $perl_code);
Here are some things it won't handle:
Undefined values
Strings containing =>
Strings containing $
Strings containing #
Strings containing non-ASCII or some non-printable characters.
As shown here:
$ perl -e'
use feature qw( say );
use Data::Dumper qw( Dumper );
local $Data::Dumper::Useqq = 1;
local $Data::Dumper::Terse = 1;
local $Data::Dumper::Indent = 0;
say(Dumper({ x => undef }));
say(Dumper({ x => " => " }));
say(Dumper({ x => q{$} }));
say(Dumper({ x => q{#} }));
say(Dumper({ x => "\x7F" }));
'
{"x" => undef} # Gives {"x": undef} instead of {"x": null}
{"x" => " => "} # Gives {"x": ": "} instead of {"x": " => "}
{"x" => "\$"} # Gives {"x": "\$"} instead of {"x": "$"}
{"x" => "\#"} # Gives {"x": "\#"} instead of {"x": "#"}
{"x" => "\177"} # Gives {"x": "\177"} instead of {"x": "\u007f"}
Not sure where that escaping happens (if you can, give some more details)
But, try to replace => with : and \" with " and you'll have yourself a valid json.
$string = '{\"caption\" => \"Genes (Comprehensive set from GENCODE 26)\",\"colour_key\" => \"[biotype]\",\"default\" => {\"MultiBottom\" => \"collapsed_label\",\"MultiTop\" => \"gene_label\",\"alignsliceviewbottom\" => \"as_collapsed_label\",\"contigviewbottom\" => \"transcript_label\",\"contigviewtop\" => \"gene_label\",\"cytoview\" => \"gene_label\"},\"key\" => \"ensembl\",\"label_key\" => \"[biotype]\",\"multi_name\" => \"GENCODE 26 Comprehensive gene set\",\"name\" => \"Comprehensive Gene Annotations from GENCODE 26\"}';
$string = str_replace('\"','"', $string);
$string = str_replace('=>',':', $string);
$json = json_decode($string, true);
print_r($json);
You can check it out here: https://3v4l.org/UBmGA
Apparently this answer got more hate than i'd expect. Nevertheless, it did help OP and i'm sticking by it. In the end, this is what SO stands for.
I would like to know though... why so many downvotes? I do take constructive criticism well and would like to know how to improve future answers.
Im looking to use a PHP array obtained from a RESTful service.
They array is just a simple array outputted as follows,
array (
0 =>
stdClass::__set_state(array(
'id' => '375',
'primary_name' => 'Beaufort 3',
'price' => '',
'sqft' => '2435',
'bdrm' => '3',
'bthm' => '2.5',
'display_title' => 'Traditional A1',
'full_img_path' => '',
'thumb_path' => '',
'available_in' => 'a:2:{i:0;s:1:"2";i:1;s:1:"5";}',
'display_first' => '',
)),
)
I'm obtaining the data using file_get_contents but of course its no longer an array at this point. What is the best way to convert this back to a usable array?
I have never seen a service that provides this, probably because it is something people would avoid using, but it does look like it could be something they intend for you to be able to use with eval(). I suppose this could be intended as a convenience. I think they have made an error, though. If you use var_export, (which I assume is how this was generated) on an array like this:
$example = array (
array(
'id' => '375',
'primary_name' => 'Beaufort 3',
'price' => '',
'sqft' => '2435',
'bdrm' => '3',
'bthm' => '2.5',
'display_title' => 'Traditional A1',
'full_img_path' => '',
'thumb_path' => '',
'available_in' => 'a:2:{i:0;s:1:"2";i:1;s:1:"5";}',
'display_first' => '',
)
);
then you would get something you could eval into a variable and use in your code. However, if you var_export an array of anonymous objects instead of an array of associative arrays, you will get the type of response you are getting, which I don't know of any way to use. I would guess they are var_exporting the results of a query and they are using FETCH_OBJ instead of FETCH_ASSOC for the fetch style.
EDIT:
I was looking through the comments on var_export after writing this and came across this way of doing it that should work.
$str = str_replace("stdClass::__set_state", "(object)", $str);
eval('$array=' . $str . ';');
But just because something is possible doesn't mean we should do it.
You can convert it back into an array with eval(). http://php.net/manual/en/function.eval.php
eval('$array='.$response.';');
However, this can be dangerous, because eval will take any PHP code given it - if the service is compromised, your code would execute anything passed to it. JSON, if the service supports it, is much safer and natively supported in PHP since 5.2 via json_decode(). http://php.net/manual/en/function.json-decode.php
I'm working with this PHP Array and I'm trying to convert it into a string:
$args=shortcode_atts( array(
'setting' => 'value',
'setting' => 'value',
'setting' => 'value',
), $atts);
The result should look like this:
' "setting":"value","setting":"value" '
I'm not sure how to loop through this? I've also noticed a lot of docs online that include the comma at the end of the last array item - is this ok or should I be in the habit of not including the comma?
I believe that you are looking for json encoded data:
$json = json_encode($args);