echo results from an google safe browsing api array - php

I know this is a basic question, but I cannot figure out how to actually do this. I have read countless tutorials about it but they seemingly do not work.
var_dump($google_check);
returns the following:
string(488) "{
"matches": [
{
"threatType": "MALWARE",
"platformType": "LINUX",
"threat": {
"url": "http://malware.testing.google.test/testing/malware/"
},
"cacheDuration": "300s",
"threatEntryType": "URL"
},
{
"threatType": "MALWARE",
"platformType": "LINUX",
"threat": {
"url": "http://malware.testing.google.test/testing/malware/"
},
"cacheDuration": "300s",
"threatEntryType": "URL"
}
]
}
"
I want to echo results from the array, so something like
echo $google_check[0][matches][threat];
echo $google_check[1][matches][threat];
Problem is this returns illegal offset on matches and threat, and only echo's a single character {
What am I doing wrong? How do I echo the results from this array without dumping the entire array?

The response you recieved is in json so you'll need to first json_decode the response.
$decoded = json_decode($google_check, true);
Then you can access it like an array
echo $decoded['matches'][0]['threat'];
echo $decoded['matches'][1]['threat'];
if you want the url value you'll need to do it like this.
echo $decoded['matches'][0]['threat']['url'];
echo $decoded['matches'][1]['threat']['url'];
please also note, when looking at array keys that aren't numerical you'll need to wrap in quotes (e.g. $decoded['matches'] instead of $decoded[matches]).
Here's a quick explanation on json
https://www.tutorialspoint.com/json/json_php_example.htm

Related

Get JSON Data From .json (php)

i'm trying to get the fields "name, price, image and rarity" to show in a php file, anyone can help me? Thanks ;D
{
"status": 300,
"data": {
"date": "2019-09-16T00:00:00.000Z",
"featured": [
{
"name": "Flying Saucer",
"price": "1,200",
"images": {
"icon": icon.png",
},
"rarity": "epic",
},
I'm using this that a friend told me, but i cant put that to work :c
<?php
$response = json_decode(file_get_contents('lista.json'), true);
foreach ($response as $val) {
$item = $val['name'];
echo "<b>$item</b>";
}
?>
I'm not quite sure what you are trying to achieve. You can just access the contents via the $response array like this:
echo $response['status']; // would output 300
You can use foreach to iterate through the array. For example: If you want to output the name of every element of the array you can use:
foreach ($response['data'] as $val) { // loop through every element of the data-array (if this makes sense depends on the structure of the json file, cant tell because it's not complete)
echo $val['featured']['name'];
}
You gotta get the index in $val['data']['featured']['name'] to retrieve the name index.
When you defined the second parameter of json_decode, you said that you want your json to be parsed to an array. The brackets in the original json identify when a new index of your parsed array will begin.
I suggest you to read about json_decode and json in general:
JSON: https://www.json.org/
json_decode function: https://www.php.net/manual/en/function.json-decode.php

Get JSON Group Name By ID, Not Value

I have a valid JSON file like this:
{
"default": {
"key_value": "Default Value"
},
"test": {
"key_value": "Test Value"
}
}
I want to get the group names as a string: "default" and "test".
I know that i could use something like:
{
"general": {
"id": "default",
"key_value": "Default Value"
},
{
"id": "test",
"key_value": "Test Value"
}
}
But since my JSON is valid and my functions for reading and saving the file are already working fine, i want to achieve this with the original structure.
For experimenting I got something like:
$json = file_get_contents("file.json");
$json_data = json_decode($json, true); // I guess assoc must be true?
foreach ($json_data as $item) } // My hope was that i am able to read $item, however it is an array
echo $item["key_value"]."<br />"; // That gives me "Default Value" and "Test Value", so thats at least something
}
I guess "default" and "test" are within the first array of the json?
Now i need to find a way to read them and save them as a string.
A foreach couldn't be that wrong since if a group like "test2" is added, i want to read it aswell.
I am struggling with undefined and illegal offsets (since i cant use arrays as keys?).
Since I am getting the values with something like:
$json_data["default"]["key_value"]
I thought there is something like $json_data[0] which should be "default".
Apparently, this is also an array right? I've already looked around in the forums already, but unfortunately no one had the same JSON structure as their problems got solved.
Maybe it's just dumb to use it like this, but there must be a way to make it work right?
Possibly it's just 3 lines of code aswell and i'm not getting there right now... I've tried so much already.
Maybe you guys can help me with that.
I think what you want is this:
foreach($json_data as $key=>$value) {
echo $key, "<br />\n";
}
If you want it a bit nicer you can use array_keys():
foreach(array_keys($json_data) as $key) {
echo $key, "<br />\n";
}
You have to try this loop :
foreach ($array as $key => $value) {
// you could print here the key or value
}

json_encode - formatting issue?

I am requesting my output look like this:
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
The values are irrelevant for this example.
My code looks like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = $error_msg;
$temp_data = array();
$temp_value = '';
foreach ($zipcodes_array as $value) {
//$temp_data['zipcode'] = $value;
//$temp_value .= json_encode($temp_data);
$temp_value .= '{"zipcode":$value},';
}
//$returndata['test'] = $temp_value;
$returndata['zipcodes'] = $temp_value;
echo json_encode($returndata);
My output varies depending on my different attempts (which you can see with the commented out things) but basically, I don't understand how the 3rd part (the part with the zipcodes) doesn't have a key or a definition before the first open bracket "["
Here is the output for the code above:
{"error_num":0,"error_details":"","zipcodes":"{\"zipcode\":11111},{\"zipcode\":11112},{\"zipcode\":11113},{\"zipcode\":22222},{\"zipcode\":33333},{\"zipcode\":77325},{\"zipcode\":77338},{\"zipcode\":77339},{\"zipcode\":77345},{\"zipcode\":77346},{\"zipcode\":77347},{\"zipcode\":77396},{\"zipcode\":81501},{\"zipcode\":81502},{\"zipcode\":81503},{\"zipcode\":81504},{\"zipcode\":81505},{\"zipcode\":81506},{\"zipcode\":81507},{\"zipcode\":81508},{\"zipcode\":81509},"}
Obviously i did not show the variables being filled/created because its through MySQL. The values are irrelevant. Its the format of the output i'm trying to get down. I don't understand how they have the "zipcode": part in between {} brackets inside another section which appears to be using JSON_ENCODE
It is close but see how it still has the "zipcodes": part in there defining what key those values are on? My question is, is the "response" above being requested by a partner actually in JSON_ENCODE format?? or is it in some custom format which I'll just have to make w/out using any json features of PHP? I can easily write that but based on the way it looks in the example above (the response) I was thinking it was JSON_ENCODE being used.
Also, it keeps putting the \'s in front of the " which isn't right either. I know it's probably doing that because i'm json_encode'ing a string. Hopefully you see what i'm trying to do.
If this is just custom stuff made to resemble JSON, I apologize. I've tried to ask the partner but I guess i'm not asking the right questions (or the right person). They can never seem to give me answers.
EDIT: notice my output also doesn't have any [ or ] in it. but some of my test JSON_ENCODE stuff has had those in it. I'm sure its just me failing here i just cant figure it out.
If you want your output to look like the JSON output at the very top of your question, write the code like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = array();
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => (int)$value);
}
echo 'Response ' . json_encode($returndata);
This will return JSON formatted like you requested above.
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
Can you just use single ZipCode object as associative array, push all your small ZipCode objects to the ZipCodes array and encode whole data structure. Here is the code example:
$returndata = array(
'error_num' => $error_code,
'error_details' => array()
);
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => $value);
}
echo json_encode($returndata);

Pull specific value from JSON with PHP

I'm trying to pull the price from the following JSON but can't seem to figure out how to reference the actual values:
{"cards": [ { "high": "0.73", "volume": 1, "percent_change": "-2.67", "name": "Lightning Bolt", "url": "http://blacklotusproject.com/cards/Revised+Edition/Lightning+Bolt/", "price": "0.73", "set_code": "3ED", "average": "0.73", "change": "-0.02", "low": "0.73"}], "currency": "USD" }
So far I've got this code, which gets into the cards array but I'm unsure how to get farther - every attempt I've tried returns null.
$json = file_get_contents($url); $data = json_decode($json, TRUE);
echo var_dump($data[cards]);
Can someone shed light on what I need to do?
$data['cards'] has another array within it. You will need to access this array with index 0. For instance, $data['cards'][0]['high'] and so on.
$data['cards'] is an array itself, so you could do:
foreach ($data['cards'] AS $carditem) {
echo $carditem['high'];
...
}
to get all items in that array,
or if you only want the first item $data['cards'][0]['...']
To access using a string literal array index, always use quotes.
$data["cards"]
Link: PHP Documentation for Arrays

Manipulating data from a JSON feed to display it

{
"Group": [
{
"name": "HolderOne",
"operators": [
{
"username": "ken",
"status": 3
},
.....etc.....
The JSON feed I am attempting to manipulate has to format above.
I wish to be able to display username and status.
$json = file_get_contents("urlhere");
$obj=json_decode($json);
echo $obj->username;
echo $obj->status;
This obviously doesn't work as they are nested(?) within the feed...I have tried:
$obj->Group[0]->name->operators->username
and
$obj->Group[0]->name->username
to no avail (as well as json_decode with ,true and ['name'], etc).
Am I being particularly dim?
when I do a var dump, the data is being collected from the feed okay.
The best way to figure this out is to iteratively do print_r's:
print_r($obj)
//prints what you see above
print_r($obj['Group']
//prints the Group Object
print_r($obj['Group'][0])
//prints first element in Group Object
print_r($obj['Group'][0]['operators'])
//etc.....
That's how I find out how to access these deep elements if I get a little stuck. Though it appears to me that you want:
$obj->Group[0]->operators[0]->username

Categories