accessing $_POST array variables in php - php

I'm able to access my $_POST array values, but can't seem to get the correct syntax for returning only the "data" part of the array. If I run var_dump($_POST["attributes"]);, I receive the following in the response callback(which is exactly what I expected):
string '{
"device_maker" = unknown;
"device_model" = Simulator;
"first_visit" = "1387478168.109";
"last_visit" = "1388358490.638";
latitude = "37.78583526611328";
locale = en;
longitude = "-122.4064178466797";
"opted_in" = 1;
"opted_out" = 0;
"os_platform" = "iPhone OS";
"os_version" = "7.0.3";
"this_visit" = "1387478168.109";
"user_id" = 1;
}' (length=389)
If I try to access any one of the attributes separately, like var_dump($_POST["attributes"]["device_model"]);, all I get in return is string '{' (length=1). I'm apparently missing a key idea on parsing this data. How do I parse "attributes" so I can place each one of the listed values into an insert statement(I've got that part ready to go once I get the data)? Granted, my php is very rusty. So I may be overlooking something obvious.
It's frustrating to see the data I need and not know how to correctly access it. So, any help is appreciated. Please ask if you need clarification.

Apparently the string being retrieved in your POST is not valid JSON. If you can't replace the values being sent to the server, you can always do a (dirty) workaround:
First, replace some characters to make it a valid json:
$jsonStr = str_replace('=', ':', $_POST["attributes"]);
$jsonStr = str_replace(';', ',', $jsonStr);
$jsonStr = str_replace(',}', '}', $jsonStr);
Then we can try to parse it using the json_decode function:
$jsonArray = json_decode($jsonStr);
Now you can access it as a regular associative array, e.g.:
echo $jsonArray['device_model'];

What you show here looks like JSON encoded data - it's a single string so there is no $_POST["attributes"]["device_model"].
You can access the data embedded in the attributes variable by converting it from JSON:
$a_string='{
"device_maker" = unknown;
"device_model" = Simulator;
"first_visit" = "1387478168.109";
"last_visit" = "1388358490.638";
latitude = "37.78583526611328";
locale = en;
longitude = "-122.4064178466797";
"opted_in" = 1;
"opted_out" = 0;
"os_platform" = "iPhone OS";
"os_version" = "7.0.3";
"this_visit" = "1387478168.109";
"user_id" = 1;
}';
// or $astring=$_POST['attributes']
$data=json_decode($a_string);
print $data['device_model'];
....but you need to verify the origin of the data - if it' not JSON, then this will break at some point.

Related

Json string conversion to json object

I have been stuck in this issue and cant seem to fix it.. I have this JSON STRING
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
I need to convert it into array of object or maybe just one json object.. I have tried doing
json_decode($unBilledArr , true);
It gives me null.
Already tried these solutions as well
Convert a string to JSON object php
https://jonsuh.com/blog/convert-loop-through-json-php-javascript-arrays-objects/
I must be doing something wrong.. cant seem to figure out what..
P.s : This is the response i am getting and i can not do anything about the response.
You are trying to decode an array, either specify the specific item within the array, or make it a string.
For instance:
$unBillableArr = '{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}';
$json = json_decode($unBillableArr, true);
// Or
$unBillableArr = ['{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}'];
$json = json_decode($unBillableArr[0], true);
However, given the string you are receiving does not contain valid JSON and you are unable to control what you receive, I have prepared the following that will replace the single quotes in your JSON, and decode each item into an array:
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
// Loop through each JSON string
$jsonObjects = []; // Change this name...
foreach ($unBillableArr as $jsonString) {
$jsonObjects[] = json_decode(str_replace("'", '"', $jsonString), true);
}
print_r($jsonObjects); // Proof it works
Please bear in mind that I would consider this to be a dirty fix. To fix this properly, you should go back to the source and ensure that the JSON they are returning to you is valid.

Get JSON result of ethereum stats with php

Need your help. I have a json array:
ethereumStats = {"blockTime": 16.890625, "lastUpdate": 1497042002.725094, "priceUsd": 275.742, "difficulty": 663594472929704.8};
How can i get the result of each data from array.
i tried this way:
$info = file_get_contents("http://alpha61.com/ethereum.json");
$result = json_decode($info,true);
$blockTime = $result["priceUsd"];
But it does'n work.
Here's something I threw together to parse out the JSON string from the file that is returned:
$info = file_get_contents("http://alpha61.com/ethereum.json");
$data = explode(" = ", $info);
$json = rtrim($data[1],";");
$result = json_decode($json,true)
$blockTime = $result["priceUsd"];
The file you are requesting was meant to be used in a javascript tag, like this <script src="http://alpha61.com/ethereum.json"></script>, so its a little awkward to pull the JSON out of it for use in php

Parsing JSON with PHP array/object confusion

I am trying to parse this JSON data to print on a fanpage I am working on.
If you look at that JSON link, you will see that the structure is [{key:value,key:value,key:value}]. I recently learned how to parse JSON with a slightly different structure like this JSON file, where the data structure is {"identifier":[{key:value,value,value,value,value}{key:value,value...}]}
Here is my code I am attempting:(I have tried about 10 variations of this with explodes for the commas too)
<?php
$json = file_get_contents('http://live.nhl.com/GameData/SeasonSchedule-20152016.json');
$json = json_decode($json, TRUE);
foreach($json as $d){
$estTime = $d['est'];
echo $estTime;
?>
As I said, I had some success with that other structure of JSON I linked by doing this:
$json = file_get_contents('http://nhlwc.cdnak.neulion.com/fs1/nhl/league/playerstatsline/20152016/2/SJS/iphone/playerstatsline.json');
$json = json_decode($json, TRUE);
$skaterData = $json['skaterData'];
$goalieData = $json['goalieData'];
foreach($skaterData as $d){
$stats = explode(',', $d['data']);
$number = $stats[0];
$position = $stats[1];
$name = $stats[2];
$gp = $stats[3];
$goals = $stats[4];
$assists = $stats[5];
$points = $stats[6];
$plsmns = $stats[7];
$pim = $stats[8];
$shots = $stats[9];
$toi = $stats[10];
$pp = $stats[11];
$sh = $stats[12];
$gwg = $stats[13];
$ot = $stats[14];
Edit: JSON data successfully parsed
The only thing wrong with your code is that you are missing the closing curly bracket to your foreach.
I would strongly recommend paying attention to the error messages you get, often they will let you easily solve the problem. If your server does not display them in the browser (this is usually a good thing on live sites), you will find them in an error log somewhere on the server.
Additionally you may want to use a proper editor with linting (what is linting), which would probably have immediately notified you of this omission one way or another. One such free tool is Atom.

JSON PHP: Is this the correct way?

I just wanted some input about my use of JSON.
<?php
header('Content-Type: text/plain');
//results
$results = array();
for($i=0;$i<20;$i++)
{
$result = array();
$result['name'] = 'Test Season '.ceil(($i+1)/13).' Episode '.(($i%13)+1);
//$result['torrent'] = 'https://www.example.com/?id='.$i.'&key='.uniqid();
$result['torrents'] = array();
$c = mt_rand(1,4);
for($j=0;$j<$c;$j++)
{
$torrent = array();
$torrent['url'] = 'https://www.example.com/?id='.uniqid().'&key='.md5(uniqid());
$torrent['codec'] = $j%2 == 0 ? 'xvid' : 'h264';
$torrent['resolution'] = '720p';
$result['torrents'][] = $torrent;
}
$results[] = $result; //push
}
echo json_encode($results);
?>
This is just some test code, not an actual implementation. Am I using JSON correctly and too the fullest? Or is some better method of doing this?
I have legal torrents that I'd like to do some JSON with.
Torrents are grouped by name which contain multiple torrents (actual links to data). And other information such as codec etc.
This is my first time actually outputting JSON, would XML be better?
Are there any guides on this topic (hopefully not entire books)?
Thanks.
What you doing is right. I like to use the StdClass to make objects rather than key value arrays, just cause it looks sexier! E.g.
$torrent = new StdClass();
$torrent->url = 'https://www.example.com/?id='.uniqid().'&key='.md5(uniqid());
$torrent->codec = $j%2 == 0 ? 'xvid' : 'h264';
$torrent->resolution = '720p';
$result['torrents'][] = $torrent;
As you say you don't need to read a whole book on the matter, I would have a look here http://php.net/manual/en/book.json.php to get to grips with the basics of JSON.
In terms of JSON vs XML, I find it far easier to represent data as JSON as it is easier to fetch the specific data you want much in the same way you can access the info in a stdClass object.
[EDIT]
And as Stefan Gehrig says make sure you define your content type as "application/json".
Absolutely fine. You could only change the MIME type to be RFC 4627 compliant though: application/json.

Parsing JSON string to dictionary swift

I'm trying to access the individual member-fields of a JSON object in PHP from a JSON string but I can't to access the inner-json, all I get is Array.
This is the JSON string
data = (
{
"created_time" = "2018-10-07T04:42:39+0000";
id = 1069496473131329;
name = "NAME_0";
},
{
"created_time" = "2018-09-09T10:31:50+0000";
id = 955684974605664;
name = "NAME_1";
},
At the moment my code is:
$nameString = $_POST["nameData"];
$nameJsonString = json_encode($nameString, JSON_FORCE_OBJECT);
$jsonNameObj = json_decode($nameJsonString, true);
I've been trying to access the individual entry with:
$element = $jsonNameObj['data'][0];
But only receive Array.
Any help would be greatly appreciated,
Cheers :)
After checking the inputted JSON data, I've realised that it doesn't have a consistent form. As opposed to the overall structure being:
JSON -> List -> JSON
Instead, it's:
JSON -> List
The list contains individual elements that can be in a different order. Consequently, calling:
$element = $jsonNameObj['data'][0]['created_time'];
Works sometimes. As there are three-values/object, I can congregate these values into a trio.
I'm sure there's a way to condense this list into a fixed-JSON format but I'm not familiar with how I'd go about that.
At the moment, with a bit of logic on the back-end, I can retrieve the values.
Thanks for your help #Difster and #Osama!

Categories