make php variable from plain text get file - php

currently i am using the below code to get a file from a site which tells me the current server status of a game server. the file is in plain text format and out puts the following depending on server status:
ouput:
{ "state": "online", "numonline": "185" }
or
{ "state": "offline" }
or
{ "state": "error" }
file get code:
<?php
$value=file_get_contents('http:/example.com/server_state.aspx');
echo $value;
?>
I would like to turn the 'state' and 'numonline' into their own variables so i could output them using a if, like:
<?php
$content=file_get_contents('http://example.com/server_state.aspx');
$state <--- what i dont know how to make
$online <--- what i dont know how to make
if ($state == online) {
echo "Server: $state , Online: $online";
} else {
echo "Server: Offline";
)
?>
but i have no idea how to turn the 'state' and 'numonline' from the plain text into a variable of their own ($state and $online), how would i go about doing this?

Your data is JSON. Use json_decode to parse it into a usable form:
$data = json_decode(file_get_contents('http:/example.com/server_state.aspx'));
if (!$data) {
die("Something went wrong when reading or parsing the data");
}
switch ($data->state) {
case 'online':
// e.g. echo $data->numonline
case 'offline':
// ...
}

Use json_decode function:
$value = '{ "state": "online", "numonline": "185" }';
$json = json_decode($value, true);
print_r($json);
if ($json['state'] == 'online') {
echo "Server: " . $json['state'] . " , Online: " . $json['numonline'];
} else {
echo "Server: Offline";
}
Output:
Array
(
[state] => online
[numonline] => 185
)

I would like to turn the 'state' and 'numonline' into their own variables:
Maybe you are looking for extract,
Example:
$value = '{ "state": "online", "numonline": "185" }';
$json = json_decode($value, true);
extract($json);
//now $state is 'online' and $numonline is 185

Related

Equality comparison PHP

I'm doing this comparison below: $deviceKey == 'mobile' or $deviceKey == 'desktop'
public function syncPublisherIds (string $publisherId, Request $request):array
{
file_put_contents('/var/log/php/burner.log', json_encode($request->getContent()) . PHP_EOL, FILE_APPEND);
$idSyncConfig = json_decode($request->getContent());
$idSyncResponseObject = new \stdClass();
foreach($idSyncConfig as $deviceKey => $deviceValue) {
// file_put_contents('/var/log/php/burner.log', json_encode(gettype($deviceKey)) . ' '. json_encode($deviceValue) . PHP_EOL, FILE_APPEND);
// $deviceKey = json_encode($deviceKey);
// add device type to object
if ($deviceKey == 'mobile' or $deviceKey == 'desktop') {
$idSyncResponseObject[$deviceKey] = new \stdClass();
} else {
throw ((new BadRequestException("Platforms must be of type 'mobile' or 'desktop', you sent type of: $deviceKey"))->errorize());
}
}
}
For some reason it hits the else statement when they are seemingly the same:
"Platforms must be of type 'mobile' or 'desktop', you sent type of: \"mobile\""
This is a Laravel endpoint.
<?php
function testForLuke(string $requestContent): void
{
$idSyncConfig = json_decode(stripslashes($requestContent));
//print_r([$requestContent, $idSyncConfig]);
foreach ($idSyncConfig as $deviceKey => $deviceValue) {
//print_r([$deviceKey, $deviceValue]);
if ($deviceKey === 'mobile' || $deviceKey === 'desktop') {
echo "great success with deviceKey of '${deviceKey}'!\n";
} else {
echo "error condition throw exception\n";
}
}
}
testForLuke('{ "mobile": { "id": 1 } }');
testForLuke('{ "desktop": { "id": 1 } }');
testForLuke('{ "derptop": { "id": 1 } }');
testForLuke("{ \"mobile\": { \"id\": 1 } }");
testForLuke("{ \"desktop\": { \"id\": 1 } }");
For me yields:
great success with deviceKey of 'mobile'!
great success with deviceKey of 'desktop'!
error condition throw exception
great success with deviceKey of 'mobile'!
great success with deviceKey of 'desktop'!
The code seems to be working already, but is highly dependent on the structure of the provided JSON, so depending on the structure of the request you may still have issues, let us know.
Edit: After re-looking, it seems like you've got backslashes in your JSON request. Are you encoding it yourself? If so you should use json_encode($response, JSON_UNESCAPED_SLASHES);
If you can't control how it is encoded for whatever you reason, you could consider using:
$idSyncConfig = json_decode(stripslashes($requestContent));

Fragmenting incoming data with PHP Json

The form of the incoming json data:
{
"statusCode": 200,
"message": "success",
"result": [
{
"longitude": -87.06687,
"start_location_latitude": 20.63589,
"start_location_longitude": -87.06687,
"end_location_latitude": 20.63589,
"end_location_longitude": -87.06687,
"highlights": [
{
"title": "Oh Yes...Mezcal Shots",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Mezcal_Shot.jpg"
},
{
"title": "Playa Del Carmen Beachfront",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen-Beach_Punta_Esmeralda.jpg"
},
{
"title": "Visit the Market",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen.jpg"
}
]
}
]
}
This incoming data is combined into a single line.
https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Mezcal_Shot.jpghttps://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen-Beach_Punta_Esmeralda.jpghttps://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen.jpg
But what I want to do is to get the first 4 of these data, for example, by throwing them into separate variables and using them. However, I was never able to do that.
My code:
foreach($UnlockData as $highlights)
{
foreach($highlights as $SingleImage)
{
if(strlen($SingleImage['url']) > 3) {
echo $SingleImage['url'];
}
}
}
This will return the first 4 highlights from each entry in result. I am using the json object vs array because I find using it as objects makes for easier to read code.
<?php
$json = json_decode($incomingJSON);
foreach ($json->result as $result) {
$ctr = 0 ;
foreach($result->highlights as $highlight) {
if (strlen($highlight->url) < 5) continue;
echo "<P>" . $highlight->title. " - " . $highlight->url;
$ctr ++;
if ($ctr>3) break;
}
}
If there is ever only one result then just get all the url from highlights (not clear why the strlen):
$urls = array_column($array['result'][0]['highlights'], 'url');
foreach($urls as $url) {
if(strlen($url) > 3) {
echo $url;
}
}
If there are multiple result then get all the highlights and then get all the url from that:
$urls = array_column(array_column($array['result'], 'highlights'), 'url']);

Why is this json value not a PHP array key?

When parsing the json below, the PHP statement:
if (array_key_exists($json_a["Guids"][$g]["Broke"][$b][$a])) {
never evaluates to true despite that "Demo" is a "key" as shown from the print_r statement.
What am I doing wrong on how I'm testing to see if "Demo" or "Live" actually exists in the json? (one or the other or both may be there for any given record)
Thank you.
Json:
{
"MinimumVersion": "20191101",
"Guids": {
"0ebe7e53-12fc-4f8f-a873-4872fe30bbee": {
"Broke": {
"Yes": {
"Demo" : { "Expires" : "" },
"Live" : { "Expires" : "" }
},
"No": {
"Demo" : { "Expires" : "20191104" },
"Live" : { "Expries" : "" }
}
},
"Message": "You need to upgrade to the latest version."
}
}
}
PHP:
<?php
$string = file_get_contents("json.txt");
$json_a = json_decode($string,true);
$g = "0ebe7e53-12fc-4f8f-a873-4872fe30bbee";
$b = "No";
$a = "Demo";
echo "G: \"" . $g . "\"<br>";
echo "B: \"" . $b . "\"<br>";
echo "A: \"" . $a . "\"<br>";
if (is_array($json_a["Guids"][$g]["Broke"][$b][$a])) {
#This next line prints Array ([0] => Expires )
print_r(array_keys($json_a["Guids"][$g]["Broke"][$b][$a]));
} else {
echo "Test: false";
}
if (array_key_exists($g,$json_a["Guids"])) {
echo ("true1");
if (array_key_exists($b,$json_a["Guids"][$g]["Broke"])) {
echo ("true2");
if (array_key_exists($json_a["Guids"][$g]["Broke"][$b][$a])) {
#this never evaluates to true. Why? "Demo" is a "key" as shown from the print_r results statement above.
echo "Value:\"" . $json_a["Guids"][$g]["Broke"][$b][$a] . "\"<br>";
}
}
}
?>
You're not using array_key_exists properly for that particular case (you use it correctly elsewhere). The correct usage is
array_key_exists ( mixed $key , array $array )
so for what you want to check, you should use
array_key_exists($a, $json_a["Guids"][$g]["Broke"][$b]);

How do I print the success message

How do I print the success message in this JSON code using PHP
{
"status": 0,
" result":{
"status":"success"
}
}
$response = {"status":"success"};
$data = json_decode(response ,TRUE); //converts to associative array
if($data['status'] == 'success'){
echo 'You are success';
}
$result = json_decode('{
"status": 0,
" result":{
"status":"success"
}
}');
echo $result['result']['status'];
Convert this json to PHP Array using json_decode()
Check the ['result']['status']
if its equals to 'success'
Then print some message

PHP JSON array issue

I have tryed almost everything to get the data in observations in a foreach sentence in php but can get it to output any data.
I Want to get the observations rows listed so i can insert it into a MySQL DB
{
"version":"2.0","secret":"meraki","type":"DevicesSeen","data":{
"apMac":"88:15:44:84:4c:90","apFloors":[],"apTags":["","recently-added",""]
,"observations":[{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":0.2907945825483442,"x":[],"y":[]},"seenTime":"2017-05-20T12:24:43Z","ssid":null,"os":"Cisco/Linksys Router","clientMac":"94:9f:3e:06:c1:6c","seenEpoch":1495283083,"rssi":47,"ipv6":null,"manufacturer":"Sonos"},{
"ipv4":"/10.226.198.65","location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":5.374873752610671,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:30Z","ssid":"DanfossConnect","os":"Slingbox","clientMac":"00:11:f6:f3:43:06","seenEpoch":1495283130,"rssi":46,"ipv6":null,"manufacturer":"Asia Pacific Microsystems"},{
"ipv4":"/172.16.0.25","location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":33.788906850703945,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:29Z","ssid":"Wireless WiFi","os":"HP Printer","clientMac":"c4:34:6b:08:dc:6d","seenEpoch":1495283129,"rssi":13,"ipv6":null,"manufacturer":"Hewlett-Packard"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":14.90854452921782,"x":[],"y":[]},"seenTime":"2017-05-20T12:24:45Z","ssid":null,"os":null,"clientMac":"54:60:09:0e:08:d2","seenEpoch":1495283085,"rssi":31,"ipv6":null,"manufacturer":"Google"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":0.287722117087862,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:54Z","ssid":null,"os":null,"clientMac":"94:9f:3e:06:c1:6d","seenEpoch":1495283154,"rssi":46,"ipv6":null,"manufacturer":"Sonos"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":4.189862222398972,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:49Z","ssid":null,"os":"Cisco/Linksys Router","clientMac":"5c:aa:fd:40:29:78","seenEpoch":1495283149,"rssi":41,"ipv6":null,"manufacturer":"Sonos"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":38.279358673491906,"x":[],"y":[]},"seenTime":"2017-05-20T12:23:18Z","ssid":null,"os":null,"clientMac":"f4:42:8f:c3:84:8b","seenEpoch":1495282998,"rssi":16,"ipv6":null,"manufacturer":"Samsung"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":39.49058481097055,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:28Z","ssid":null,"os":null,"clientMac":"a0:8c:fd:06:ec:17","seenEpoch":1495283128,"rssi":9,"ipv6":null,"manufacturer":"Hewlett-Packard"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":4.966494178173178,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:49Z","ssid":null,"os":null,"clientMac":"5c:aa:fd:40:29:79","seenEpoch":1495283149,"rssi":40,"ipv6":null,"manufacturer":"Sonos"},{
"ipv4":null,"location":{"lat":56.46452206894476,"lng":9.39005605565066,"unc":28.907921961158962,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:22Z","ssid":null,"os":"iOS","clientMac":"b0:70:2d:84:38:cf","seenEpoch":1495283122,"rssi":13,"ipv6":null,"manufacturer":"Apple"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":40.978157267912586,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:34Z","ssid":null,"os":null,"clientMac":"60:6d:c7:85:91:17","seenEpoch":1495283134,"rssi":20,"ipv6":null,"manufacturer":"Hon Hai/Foxconn"}
]
}
}
https://jsonlint.com/ Your json code has syntax problem! one } was missing! Then go ahead with the other answers :)
<?php
$something = json_decode('{
"version":"2.0",
"secret":"meraki",
"type":"DevicesSeen",
"data":{
"apMac":"88:15:44:84:4c:90",
"apFloors":[],
"apTags":["","recently-added",""],
"observations":[{
"ipv4":null,
"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":0.2907945825483442,"x":[],"y":[]},
"seenTime":"2017-05-20T12:24:43Z",
"ssid":null,
"os":"Cisco/Linksys Router",
"clientMac":"94:9f:3e:06:c1:6c",
"seenEpoch":1495283083,
"rssi":47,
"ipv6":null,
"manufacturer":"Sonos"
},{
"ipv4":"/10.226.198.65","location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":5.374873752610671,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:30Z","ssid":"DanfossConnect","os":"Slingbox","clientMac":"00:11:f6:f3:43:06","seenEpoch":1495283130,"rssi":46,"ipv6":null,"manufacturer":"Asia Pacific Microsystems"},{
"ipv4":"/172.16.0.25","location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":33.788906850703945,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:29Z","ssid":"Wireless WiFi","os":"HP Printer","clientMac":"c4:34:6b:08:dc:6d","seenEpoch":1495283129,"rssi":13,"ipv6":null,"manufacturer":"Hewlett-Packard"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":14.90854452921782,"x":[],"y":[]},"seenTime":"2017-05-20T12:24:45Z","ssid":null,"os":null,"clientMac":"54:60:09:0e:08:d2","seenEpoch":1495283085,"rssi":31,"ipv6":null,"manufacturer":"Google"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":0.287722117087862,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:54Z","ssid":null,"os":null,"clientMac":"94:9f:3e:06:c1:6d","seenEpoch":1495283154,"rssi":46,"ipv6":null,"manufacturer":"Sonos"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":4.189862222398972,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:49Z","ssid":null,"os":"Cisco/Linksys Router","clientMac":"5c:aa:fd:40:29:78","seenEpoch":1495283149,"rssi":41,"ipv6":null,"manufacturer":"Sonos"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":38.279358673491906,"x":[],"y":[]},"seenTime":"2017-05-20T12:23:18Z","ssid":null,"os":null,"clientMac":"f4:42:8f:c3:84:8b","seenEpoch":1495282998,"rssi":16,"ipv6":null,"manufacturer":"Samsung"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":39.49058481097055,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:28Z","ssid":null,"os":null,"clientMac":"a0:8c:fd:06:ec:17","seenEpoch":1495283128,"rssi":9,"ipv6":null,"manufacturer":"Hewlett-Packard"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":4.966494178173178,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:49Z","ssid":null,"os":null,"clientMac":"5c:aa:fd:40:29:79","seenEpoch":1495283149,"rssi":40,"ipv6":null,"manufacturer":"Sonos"},{
"ipv4":null,"location":{"lat":56.46452206894476,"lng":9.39005605565066,"unc":28.907921961158962,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:22Z","ssid":null,"os":"iOS","clientMac":"b0:70:2d:84:38:cf","seenEpoch":1495283122,"rssi":13,"ipv6":null,"manufacturer":"Apple"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":40.978157267912586,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:34Z","ssid":null,"os":null,"clientMac":"60:6d:c7:85:91:17","seenEpoch":1495283134,"rssi":20,"ipv6":null,"manufacturer":"Hon Hai/Foxconn"}]
}
}');
foreach($something->data->observations[0] as $key => $val){
if($key === "location"){
echo '<hr><h4>here is the location object</h4>';
foreach($something->data->observations[0]->$key as $item => $data){
print_r(['item'=>$item,'data'=>$data]);
}
echo '<hr>';
}
print_r($something->data->observations[0]->$key);
foreach($something->data->observations[0]->$key as $item => $data){
if($item === '')
print_r(['item'=>$item,'data'=>$data]);
}
print_r(['key'=>$key,'val'=>$val]);
echo '<br>';
}
echo '<hr>';
print_r($something->data->observations[0]);
echo '<hr>';
print_r($something);
echo '<hr>';
exit;
<?php
// you have to use json_decode for sure
$something = json_decode('{
"version":"2.0","secret":"meraki","type":"DevicesSeen","data":{
"apMac":"88:15:44:84:4c:90","apFloors":[],"apTags":["","recently-added",""]
,"observations":[{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":0.2907945825483442,"x":[],"y":[]},"seenTime":"2017-05-20T12:24:43Z","ssid":null,"os":"Cisco/Linksys Router","clientMac":"94:9f:3e:06:c1:6c","seenEpoch":1495283083,"rssi":47,"ipv6":null,"manufacturer":"Sonos"},{
"ipv4":"/10.226.198.65","location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":5.374873752610671,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:30Z","ssid":"DanfossConnect","os":"Slingbox","clientMac":"00:11:f6:f3:43:06","seenEpoch":1495283130,"rssi":46,"ipv6":null,"manufacturer":"Asia Pacific Microsystems"},{
"ipv4":"/172.16.0.25","location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":33.788906850703945,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:29Z","ssid":"Wireless WiFi","os":"HP Printer","clientMac":"c4:34:6b:08:dc:6d","seenEpoch":1495283129,"rssi":13,"ipv6":null,"manufacturer":"Hewlett-Packard"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":14.90854452921782,"x":[],"y":[]},"seenTime":"2017-05-20T12:24:45Z","ssid":null,"os":null,"clientMac":"54:60:09:0e:08:d2","seenEpoch":1495283085,"rssi":31,"ipv6":null,"manufacturer":"Google"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":0.287722117087862,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:54Z","ssid":null,"os":null,"clientMac":"94:9f:3e:06:c1:6d","seenEpoch":1495283154,"rssi":46,"ipv6":null,"manufacturer":"Sonos"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":4.189862222398972,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:49Z","ssid":null,"os":"Cisco/Linksys Router","clientMac":"5c:aa:fd:40:29:78","seenEpoch":1495283149,"rssi":41,"ipv6":null,"manufacturer":"Sonos"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":38.279358673491906,"x":[],"y":[]},"seenTime":"2017-05-20T12:23:18Z","ssid":null,"os":null,"clientMac":"f4:42:8f:c3:84:8b","seenEpoch":1495282998,"rssi":16,"ipv6":null,"manufacturer":"Samsung"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":39.49058481097055,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:28Z","ssid":null,"os":null,"clientMac":"a0:8c:fd:06:ec:17","seenEpoch":1495283128,"rssi":9,"ipv6":null,"manufacturer":"Hewlett-Packard"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":4.966494178173178,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:49Z","ssid":null,"os":null,"clientMac":"5c:aa:fd:40:29:79","seenEpoch":1495283149,"rssi":40,"ipv6":null,"manufacturer":"Sonos"},{
"ipv4":null,"location":{"lat":56.46452206894476,"lng":9.39005605565066,"unc":28.907921961158962,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:22Z","ssid":null,"os":"iOS","clientMac":"b0:70:2d:84:38:cf","seenEpoch":1495283122,"rssi":13,"ipv6":null,"manufacturer":"Apple"},{
"ipv4":null,"location":{"lat":56.46451920053334,"lng":9.390050682697847,"unc":40.978157267912586,"x":[],"y":[]},"seenTime":"2017-05-20T12:25:34Z","ssid":null,"os":null,"clientMac":"60:6d:c7:85:91:17","seenEpoch":1495283134,"rssi":20,"ipv6":null,"manufacturer":"Hon Hai/Foxconn"}
]
}
}',true);
// first of all you miss an {
// use the second argument "true" to make it return an array
foreach ( $something['data']['observations'] as $item ){
$location_lng = $item['location']['lng'];
$location_lat = $item['location']['lat'];
echo $location_lng;
echo '<hr>';
echo $location_lat;
// Everything is good :)
}
?>

Categories