Unable to eval a string array - php

How can i change this to a JSON Array? im using the eval technique but this is not working. Im getting this kind of response from our upx server:
array(
'invoice' => array(
'id' => '4',
'realid' => '4',
'address_rev' => NULL,
'relation_data_id' => '3',
'contact_set_rev' => '3',
'business_data_rev' => '4',
'private_data_rev' => NULL,
// etc..
)
);
var_dump($newdata); // String
eval("\$newdata = \"$newdata\";");
var_dump($newdata); // Still stays as a string as shown above....
Any clue?
Ty Already!

You'll facepalm really bad when I tell you this..
But the reason it's still a string is because you wrapped it in "" inside your call to eval, and of course wrapping letters inside of quotes will make it.. (drum roll ..) a string.
eval ('$newdata = ' . $newdata . ';'); // this will do what you want
If you want to turn it into json right away, use the below:
eval ('$newdata = json_encode (' . $newdata . ');');
PHP: json_encode - Manual

var_dump($newdata); // String
eval("\$newdata = $newdata;");
var_dump($newdata); // Still stays as a string as shown above....
// eval("\$newdata = \"$newdata\";");
// ^ ^
Remove the double quotes. Your just putting it back into a string...
Although as I said above, if you want to transmit a PHP array, you should be using serialize()

You can try json_encode of php. you can try
$json_array = json_encode($your_array);
This will give you json encoded array. Then you can do json_decode on $json_array to get original contents back
Check if your php has JSON extension

Related

At a loss with JSON, PHP, AS3: Cannot trace correct value

I have used JSON objects before and they work perfectly but the JSON objects that I made before have been from a result of fetched MySQL entries. Now, I am trying to make my own JSON object through an array in PHP and it shows correctly in the database but I cannot access any of the values like before.
$chatArray = array(
array(
'chatusername' => 'Troy',
'chatuserid' => '123',
'chatmessage' => 'Hello World'
),
array(
'chatusername' => 'Nick',
'chatuserid' => '124',
'chatmessage' => 'Testing'
));
$inputArray = json_encode($chatArray);
That is what I input into my database and like I said it works good. Then I call for it in a separate .php and get this
{"chat":"[{\"chatuserid\": \"123\", \"chatmessage\": \"Hello World\", \"chatusername\": \"Troy\"}, {\"chatuserid\": \"124\", \"chatmessage\": \"Testing\", \"chatusername\": \"Nick\"}]"}
It throws the "chat" out front which is the column name in my database which I am not sure why.
When I trace it I can only seem to trace it by
var messageArray:Object = JSON.parse(event.target.data);
trace(messageArray.chat);
Any time I try to reference say messageArray.chat.chatusername it returns an error.
I'm sorry I know it is probably a simple solution but I have been searching and working at it for a few hours now.
Any help is much appreciated! Thank you!
From the PHP code that generates your JSON output:
$stmt = $conn->prepare("SELECT chat FROM markerinfo WHERE markerid='$chatid'");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Keep in mind that the chat column in your database contains a JSON-string.
This code is not decoding the JSON-string in your database, so $result will be an array containing a JSON-string as well:
$result = [
'chat' => '[{"chatusername":"Troy","chatuserid":"123","chatmessage":"Hello World"},{"chatusername":"Nick","chatuserid":"124","chatmessage":"Testing"}]'
];
By passing that array through json_encode(), you're double-encoding your JSON-string.
For your purposes, you can probably get away with:
echo $result['chat'];
But, if you want the chat column name to be included in your output, you will have to decode the stored JSON first:
$result['chat'] = json_decode($result['chat']);
echo json_encode($result);
Probably this is related to the php side when it encodes your array, it will escape it with slashes, and this confuses the JSON parsing in your JS side. Try to add the JSON_UNESCAPED_SLASHES option to your json_encode function like this:
$inputArray = json_encode($chatArray, JSON_UNESCAPED_SLASHES);
Check the json_encode function documentation for more details:
http://php.net/manual/en/function.json-encode.php

How to remove quotes from numerical array value

How can I let my PHP server respond with some thing like this:
{"eCode":0,"city":"london","time":"15:35"}
not:
{"eCode":"0","city":"london","time":"15:35"}
I'm using this PHP code:
<?php
$data = array('eCode' => '0', 'city' => 'london', 'time' => '15:35');
header('Content-type: application/json');
echo json_encode($data);
?>
So how can I remove the quotes from "eCode":"0", and replace it with "eCode":0, ?
You're quoting the zero, making it a string. Just leave it as a int:
<?php
$data = array('eCode' => 0, 'city' => 'london', 'time' => '15:35');
echo json_encode($data);
?>
This answer reiterates some things that were already said by others, but hopefully a little more explanation will be helpful.
Basically, the zero is quoted in the output of json_encode($data) because it is quoted in the input.
json_encode will not automatically convert numeric strings to integers, unless you have set the JSON_NUMERIC_CHECK option, for example:
echo json_encode($data, JSON_NUMERIC_CHECK);
If you are constructing the array you're attempting to json_encode with your code, then you should be able to simply add ints rather than numeric strings into the array as you build it:
$data['eCode'] = 0; // use 0 instead of '0'
$data['city'] = 'london';
$data['time'] = '15:35';
However, if the array you're working with is coming from some other source, such as a query result, you'll need to decide between several options:
Use JSON_NUMERIC_CHECK when you json_encode (keep in mind that it won't only convert that column to a number; it will convert anything that looks like a number - you can see various warnings about that in the comments on this answer and on the PHP documentation)
Figure out how to make adjustments to the data source or the way you fetch the data so that the array you get will already have ints instead of strings (for example, turning off emulated prepares in PDO)
Convert the value in the array before you json_encode. There are various ways to do that, $data['eCode'] = (int) $data['eCode'];, for example.
In my opinion, option 2 would be the best way to handle it.

how can I correct php/json syntax error?

I can retun this with json/php
exit('[{"name":"signup","state":"1","message":"this is a message"}]');
but not this:
$_SESSION["message"] = 'link: here ';
exit('[{"name":"signup","state":"1","message":"'.$_SESSION['message'].'"}]');
how can correct it?
JSON uses double quotes to encapsulate strings, and you're simply concatenating in a string that contains unescaped double quotes which breaks the encoding.
To ensure that all of your data is encapsulated and encoded properly do something like:
$data = [
'name' => 'signup',
'state' => '1',
'message' => $_SESSION['message']
];
echo json_encode($data);
exit();
json_encode() handles escaping, encoding, conversions, and anything else necessary to produce properly-formatted JSON.
If you want this at easiest way , follow my steps.
Dont make JSON manually..
Use this:
Make an array first.
Than use json_encode . You will get your data. correctly.

What kind of php array is this and how do I edit it?

I am working with a project that is coded in php OOP. I have created a form that post back to itself and gets those values and puts them into a predefined array format. I say predefined because this is the way the previous coder has done it:
$plane->add(array('{"name":"Chris","age":"22"}','{"name":"Joyce","age":"45"}'));
So when I get my values from the $_POST array, I thought it would be simple, so I tried
$plane->add(array("{'name':$customerName,'age':$customerAge}"));
This is triggering an error though, it seems it's passing the actual name of the variable in as a string instead of it's value. So how do I pass those values in to that function. While we are on it, can someone explain what kind of array that is, I thought arrays were always $key=>value set, not $key:$value.
As other comments and answers have pointed out, the data is being serialized in a format known as JSON. I suggest reading up on json_encode() and json_decode()
To make your example work, you would have to do:
$data = array("name" => $customerName, "age" => $customerAge);
$plane->add(array(json_encode($data));
That looks like json:
http://sandbox.onlinephpfunctions.com/code/e1f358d408a53a8133d3d2e5876ef46876dff8c6
Code:
$array = json_decode('{"name":"Chris","age":"22"}');
print_r( $array );
And you can convert an array to json with:
$array = array("Customer" => "John");
$arrayJson = json_encode( $array);
So to put it in your context:
$array = array("Name"=>"Chris", "age" => 22);
$array2 = array("Name"=>"John", "age" => 26);
$plane->add(array( json_encode( $array),json_encode( $array2) );
It looks like it could be JSON, but might not be.
Be careful to quote everything like they have done, you didn't have any quotes around the name or age.
I've added the same sort of quotes, and used the backslashes so that PHP doesn't use them to end the string:
$plane->add(array("{\"name\":\"$customerName\",\"age\":\"$customerAge\"}"));
Be wary of user data, if $customerName and $customerAge come from POST data, you need to properly escape them using a well tested escaping function, not something you just hack together ;)
It looks like your array is an array of JSON encoded arrays. Try using:
$plane->add(array('{"name":"' . $nameVar . '","age":"' . $ageVar . '"}', ...));
If you use the following:
echo json_encode(array('name' => 'Me', 'age' => '75'), array('name' => 'You', 'age' => '30'));
You will get the following string:
[{"name":"Me","age":"75"},{"name":"You","age":"30"}]
I believe you are getting an error because what you are trying to pass to the function is not JSON while (It looks like ) the function expects an array json strings, Manually trying to write the string might not be a good idea as certain characters and type encode differently. Best to use json_encode to get you json string.
$plane->add(array(json_encode(array('name'=>$customerName,'age'=>$customerAge))));

How to process array returned from pgsql?

in php i get an array from pgsql:
$res = $db
->query( "SELECT myarray FROM arrays WHERE array_name=smth" )
->fetchRow();
exit (json_encode($res));
Type in pgsql is integer[]
But in JS I get JSON with one string "{1,2,3,...,}"
How to get in 'array-way' this data?
PDO does not do any kind of type translation, everything is returned as strings. So you will have to parse the string using explode() and build a PHP array yourself.
json_encode Returns a JSON encoded string on success.
Assign the values returned by fetchrow() to a variable and try to print it before json_encode . it will be an array!!!
If you want to get the JSON decoded to an array in JavaScript, you can simply use the function eval(). But first you should make sure it is a JSON string.
See more: http://json.org/js.html
You can use something like this:
$php_array = json_decode( str_replace(
array( '[', ']', '{', '}' ),
array( '\u005B', '\u005D', '[', ']' ),
$your_pgsql_array
) );

Categories