PHP Notice: Array to string conversion when echoing json_decode()'ed data - php

I have this code in a.json:
{
"body" : {
"outboundSMSMessageRequest": {
"address": [
"9456654978" /* 1 */
],
"senderAddress": " 64735 ", /* 3 */
"outboundSMSTextMessage": {
"message": "Welcome to fgf Your Confirmation Code - " /* 2 */
},
"clientCorrelator": "1", /* 4 */
"receiptRequest": {
"notifyURL": "2", /* 5 */
"callbackData": "3" /* 6 */
},
"senderName": "4" /* 7 */
}
}
}
I want to print the values as marked above (1, 3, 2, 4, 5, 6, 7, the values only). I have tried this:
$jsonData = file_get_contents("a.json");
$json = json_decode($jsonData,true);
echo $json;
but I end up with the following notice:
PHP Notice: Array to string conversion
How can I print the values as desired?

Presumably by:
I want to in a PHP page to print (1, 3, 2, 4, 5, 6, 7, the values only)
... you mean those values you've marked with the numbered comments, e.g. /* 1 */ - if so, this should do the trick (to just echo it out anyway).
$jsonData = file_get_contents("a.json");
$o = json_decode($jsonData);
$outboundSMSRequest = $o->body->outboundSMSMessageRequest;
echo $outboundSMSRequest->address[0] . "\n" // outbound address
. $outboundSMSRequest->outboundSMSTextMessage->message . "\n" // outbound message
. $outboundSMSRequest->senderAddress . "\n" // sender address
. $outboundSMSRequest->clientCorrelator . "\n" // client correlator
. $outboundSMSRequest->receiptRequest->notifyURL . "\n" // notification URL
. $outboundSMSRequest->receiptRequest->callbackData . "\n" // callback data
. $outboundSMSRequest->senderName; // sender name
When you use json_decode() you turn the JavaScript object into a PHP object - so you just access it accordingly.

Json do not support comments so you need to remove them from your file,
see Can comments be used in JSON?

Related

Why will PHP not show all JSON data in file (or see it when referensed using key)

I have this JSON data:
{ "angus.seya#yourmum.com69420666777Google Pixel XL": [
[
"Screen Shot 2019-08-08 at 6.08.09 pm.png"
],
null,
"Google Pixel XL",
"This is a pixel XL, glass is fine, LCD brocken and mainboard broke.",
0,
[
[
"There are no messages."
],
[
"Logan Paul - Angus",
"Logan - Hi, I want a frog mask",
"Angus - Sorry, I this is about the pixel not frog mask."
]
] ]}
Pretty image version here:
I want to echo the 5th element to screen, (just a print_r which will show sub arrays too for the moment). However, my code (below) outputs this:
//OUTPUT: //DONT WORRY ABOUT ANYTHING UNTIL !ISSUE COMMENT!
//Array ( [0] => There are no messages. )
//Code:
<?php
$id = $_POST['id']; //user#domain69420666777add_name
$reply = $_POST['reply'];
$replys = explode("69420666777",$id);
$name = explode("#", $replys[0]);
$name = ($name[0]);
$craft = $name . " - " . $reply;
#echo $craft;
// JSON-- !!!!ISSUE FROM HERE ON! VVV
$jsonString = file_get_contents('../adds.json');
$id = $_GET['add'];
$data = json_decode($jsonString, true); echo "<br>";
print_r($data[$id][5])
?>
Thanks for any help. I hope I explained it well enough.
this was my fault:
Issue was this line
$id = $_GET['add'];
was overwriting this line before it.
$id = $_POST['id'];
There is no $_GET data. I forgot I pasted that in from my previous code.
Sorry.

How to update or add value to JSON [duplicate]

This question already has answers here:
Is there a JSON api based CMS that is hosted locally? [closed]
(1 answer)
Update JSON value if exists otherwise add it in PHP
(2 answers)
Closed 3 years ago.
I am running an app from AndroidHive which has feed.json which the app loads the content below from.
http://api.androidhive.info/feed/feed.json and this is the post url http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/
{
"feed": [{
"id": 1,
"name": "National Geographic Channel",
"image": "A URL",
"status": "Science and etc"
And Cosmos is all about making science an experience.
","
profilePic ": "
A URL ","
timeStamp ": "
1403375851930 ","
url ": null
}]
}
the above is the default content am wondering how to i add more to this content from or using a php script. I would love to know how to do it because I noticed that most application source code created in www_androidhive_info uses .json to load content which is an alternative to webview
You can use json_decode() function to convert JSON string to object, add your variable, and then conver the object back to JSON
$obj = json_decode($json, true);
$obj->feed[0]->url = "google.com"
:
Load the JSON
Decode the JSON
Add your content
Encode to JSON
Send it to your app
Code:
<?php
function failure($reason) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['failure' => $reason]);
exit;
}
// 1. Load the JSON
$content = file_get_contents('http://api.androidhive.info/feed/feed.json');
if (!$content) {
return failure('Failed to load upstream JSON');
}
// 2. Decode the JSON
$decodedContent = json_decode($content, true);
if ($decodedContent === false) {
return failure('Failed to parse upstream JSON');
} elseif (empty($decodedContent)) {
return failure('Upstream JSON empty');
}
// 3. Add your content
$decodedContent['feed'][] = [
"id": 12,
"name": "An example name",
"image": "https://example.com/test_image.jpg",
"status": "Hello!",
"profilePic": "https://example.com/test_profile_pic.jpg",
"timeStamp" => time(),
"url" => "https://example.com"
];
// 4. Encode to JSON
$responseContent = json_encode($decodedContent);
// 5. Send it to your app
echo $responseContent;
Decode the JSON and make new function for changes then encode back.
<?php
$JsonVar = file_get_contents('http://api.androidhive.info/feed/feed.json');
$myjson = json_decode($JsonVar,true);
function Changes() {
$myjson->feed[2]->name = "FeedID2";
$myjson->feed[2]->id = "2";
$myjson->feed[2]->image = "link to image.png";
$myjson->feed[2]->status = "I am here.";
$myjson->feed[2]->profilePic = "link to image.png";
$myjson->feed[2]->timeStamp = time();
$myjson->feed[2]->url = 'http://url.com';
}
json_encode(Changes());
?>

How to get data from block.io webhook?

I'm using block.io api in my localhost. I've tested basic wallet api which contains generating new address, getting balance of an address, withdraw and etc. All of them works fine but I've stuck at Real-Time Notifications API. I can't get it done. I've set the call back url and I'm using testnet bitcoin network for testing. When a transaction occurs how can I get the data from POSTed notification to my callback.php page?? API sends me JSON data type like this
{
"notification_id": "..."
"delivery_attempt": 1,
"created_at": 1426104819,
"type": "address",
"data": {
"network": "BTC",
"address": "3cBraN1Q...",
"balance_change": "0.01000000", // net balance change, can be negative
"amount_sent": "0.00000000",
"amount_received": "0.01000000",
"txid": "7af5cf9f2...", // the transaction's identifier (hash)
"confirmations": X, // see below
"is_green": false // was the transaction sent by a green address?
}
}
and my callback.php code is this
require_once 'block.io/block_io.php';
$data = json_decode(file_get_contents('php://input'), true);
$type = $data['type'];
$network = $data['data']['network'];
$address = $data['data']['address'];
$balence_change = $data['data']['balance_change'];
$tx = $data['txid'];
$confirmations = $data['confirmations'];
echo 'Type: ' . $type;
echo 'Network: ' . $network;
echo 'Address: ' . $address;
echo 'Balance change: ' . $balance_change;
echo 'Confirmations: ' . $confirmations;
I use testnet to send bitcoins then refresh the page but nothing is returned. The variables are all empty. Please help me to get this done.
Thanks

PHP Parsing JSON data into variables

Alright i have been searching all over this website for some simplistic help.
A lot of the examples here are so wrapped in code it's hard to get the understanding
to implement into my own code.
I need to loop through stats on each game and display the information via variables.
Now i can do everything myself, i just can't seem to find a for each loop willing to
display my information
My current code:
$ch2 = curl_init();
// set url
curl_setopt($ch2, CURLOPT_URL, "https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/" . $myid . "/ranked?season=SEASON4&api_key=(REMOVED)");
//return the transfer as a string
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$response2 = curl_exec($ch2);
// close curl resource to free up system resources
curl_close($ch2);
$obj = json_decode($response2, true);
foreach ($obj as $val) {
echo "<b>" . $val['stats']['totalDeathsPerSession'] . "</b><br>";
echo "<b>" . $val['stats']['totalDamageTaken'] . "</b><br>";
echo "<b>" . $val['stats']['totalChampionKills'] . "</b><br>";
echo "<b>" . $val['stats']['totalDeathsPerSession'] . "</b><br>";
}
Here's the JSON data
{
"modifyDate": 1402869729000,
"champions": [
{
"id": 40,
"stats": {
"totalDeathsPerSession": 5,
"totalSessionsPlayed": 1,
"totalDamageTaken": 17488,
"totalQuadraKills": 0,
"totalTripleKills": 0,
"totalMinionKills": 15,
"maxChampionsKilled": 0,
"totalDoubleKills": 0,
"totalPhysicalDamageDealt": 6183,
"totalChampionKills": 0,
"totalAssists": 12,
"mostChampionKillsPerSession": 0,
"totalDamageDealt": 21580,
"totalFirstBlood": 0,
}
},
{
"id": 42,
"stats": {
"totalDeathsPerSession": 6,
"totalSessionsPlayed": 1,
"totalDamageTaken": 10626,
"totalQuadraKills": 0,
"totalTripleKills": 0,
"totalMinionKills": 29,
"maxChampionsKilled": 1,
"totalDoubleKills": 0,
"totalPhysicalDamageDealt": 11166,
"totalChampionKills": 1,
}
],
"summonerId": 29283170
}
it keeps going on and on, i don't want to flood the entire log here.
I am simply just trying to grab some of the data like Total Minion Kills
Total Deaths, Kills.. But it keeps coming up blank with everything i try.
I have attempted so many different ways before coming here. i really hope you can help!
It should be:
foreach ($obj['champions'] as $val) {

How to retrieve yelp category_filter with PHP? A JSON object inside a JSON object

I am working with the Yelp API v1 and i'm trying to get the category_filter which is stored in category object.A small part of my JSON looks like this:
"businesses": [
{
"address1": "800 N Point St",
"phone": "4157492060",
"categories": [{
"category_filter": "newamerican",
"search_url": "http://www.yelp.com/search?cflt=newamerican\u0026find_desc=\u0026find_loc=800+N+Point+St%2C+San+Francisco+94109",
"name": "American (New)"
}],
"name": "Gary Danko",
}]
My php script looks like this:
<?php
$yelpstring = file_get_contents("PATH TO JSON", true);
$obj = json_decode($yelpstring, true);
foreach($obj['businesses'] as $business){
echo "Restaurant name: " . $business['name']."<br/>";
echo "Restaurant Type: " . $business['categories']['category_filter']."<br/>";
echo "Address 1: " . $business['address1']."<br/>";
echo "Phone: " . $business['phone'] ."<br/>";
echo "<hr>";
}
?>
I'm getting the name,address1 and phone,but not the category_filter i get a php error that says:
"Notice: Undefined index: category_filter in file.php on line 12"
I don't understand what i am doing wrong.
$business['categories']['category_filter']
is wrong
You have to use: $business['categories'][0]['category_filter']
In your json is "[{" which means that there is an array (/object, decoded as assoc-array) in another array.

Categories