Unable to Parse JSON Fields Due to Leading Bracket in PHP - php

I'm trying to create a webhook for Mandrill that will send an e-mail to the sender when a previously sent e-mail bounces. I'm able to receive the JSON data from Mandrill, but am unable to parse that data to send to the original sender:
<?php
require_once 'mandrill-api-php/src/Mandrill.php'; //Not required with Composer
$mandrill = new Mandrill('*myapikey*');
$json = stripslashes($_POST['mandrill_events']);
$jsondata = json_decode($json,true);
$subject = $jsondata['event'];
$message = "STRIPSLASHES: ".$json."----JSONDATA----".$jsondata;
$emailAddress = "*me#mydomain.com*";
mail($emailAddress, $subject, $message);
?>
Here is what the $json data looks like in the $message variable. It is a literal copy and paste from the test e-mail I receive:
STRIPSLASHES: [{"event":"spam","msg":{"ts":1365109999,"subject":"This an example webhook message","email":"example.webhook#mandrillapp.com","sender":"example.sender#mandrillapp.com","tags":["webhook-example"],"opens":[{"ts":1365111111}],"clicks":[{"ts":1365111111,"url":"http://mandrill.com"}],"state":"sent","metadata":{"user_id":111},"_id":"exampleaaaaaaaaaaaaaaaaaaaaaaaaa","_version":"exampleaaaaaaaaaaaaaaa"},"_id":"exampleaaaaaaaaaaaaaaaaaaaaaaaaa","ts":1422475458},{"event":"spam","msg":{"ts":1365109999,"subject":"This an example webhook message","email":"example.webhook#mandrillapp.com","sender":"example.sender#mandrillapp.com","tags":["webhook-example"],"opens":[{"ts":1365111111}],"clicks":[{"ts":1365111111,"url":"http://mandrill.com"}],"state":"sent","metadata":{"user_id":111},"_id":"exampleaaaaaaaaaaaaaaaaaaaaaaaaa1","_version":"exampleaaaaaaaaaaaaaaa"},"_id":"exampleaaaaaaaaaaaaaaaaaaaaaaaaa1","ts":1422475458}]----JSONDATA----Array
I notice that the $json is outputting the json data, but has a leading and ending bracket, as opposed to starting with a squiggly bracket. So I decided to call the data as if it were an array, but to no avail.
In a test, instead of doing $json = stripslashes(... I copy and pasted the json data above as a literal string. Once I removed the leading/ending brackets, I was able to parse some data.

Why don't you try removing the brackets using PHP?
$json = ltrim($json, "[");
$json = rtrim($json, ']");
And then pass it to the decoder?

Actually, I was able to fix it by "grabbing" the json data a different way, formatting it correctly as I receive it:
$rawdata = file_get_contents('php://input');
$decodeurl = urldecode($data);
$jsonready = substr($decodeurl, 16);
$data = json_decode($jsonready, true);
$recipient = $data['0']['msg']['email'];
//etc, etc, etc
I followed this example:
https://sendy.co/forum/discussion/1137/using-mandrill-webhook-for-bounces-complaints/p1
I hope this helps people who are trying to utilize Mandrill's API!

Related

PHP decode JSON from Android

I post a JSON from Android to PHP:
{"0":{"nome":"name","cf":"0101","address":"STREET 123"},"1":{"codice":"123","nome":"ACQUA","quantita":"3"},"2":{"codice":"123","nome":"ACQUA","quantita":"3"}}
In php i need to get user info always 0 (nome, cf and address) after this i need a while for getting dynamic element 1,2,3,4 etc etc (in while) always codice, nome and quantita but i have tried some code in php like:
$string = {"0":{"nome":"name","cf":"0101","address":"STREET 123"},"1":{"codice":"123","nome":"ACQUA","quantita":"3"},"2":{"codice":"123","nome":"ACQUA","quantita":"3"}};
$string = json_encode($string);
$nome = json_decode ($string, true);
echo $nome[0]->nome; //for single user info
but result is always white page
There are a few mistakes in the code...
$string = '{"0":{"nome":"name","cf":"0101","address":"STREET 123"},"1":{"codice":"123","nome":"ACQUA","quantita":"3"},"2":{"codice":"123","nome":"ACQUA","quantita":"3"}}';
//$string = json_encode($string);
$nome = json_decode ($string, true);
echo $nome[0]['nome']; //for single user info
The first line needs single quotes round it.
The json_encode() isn't needed as it's already JSON.
The last line needs to use ['nome'] as it's using arrays (by using true as the second parameter to json_decode())

Formatting JSON formatted text file in PHP

So I got a HTML page with a button. When I click the button, a separate javascript file sends a GET request to my PHP file, expecting a JSON object in return. My PHP reads a JSON formatted text file and should convert it into a JSONObject and echo it out for my javascipt. I had some code working before, but it doesn't seem to do it anymore since I changed to a Ajax aproach instead of having everything in the same file. This is my code:
readLog.php
<?php
class test{
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
function getLog(){
header('Content-Type: application/json');
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
echo json_encode($logLines);
}
}
?>
My humid.log file looks like this:
{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }
{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }
Now If I press my button, this is the response I get checking the console in my web browser:
Response:
["{\"date\":\"26\/09\/2016\", \"time\":\"22:40:46\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }{\"date\":\"26\/09\/2016\", \"time\":\"23:10:47\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }\n"]
JSON:
"{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }\n"
obviously something is wrong with the formatting, but I don't know what. As I said, this code worked just fine when I had my php and HTML in the same file.
EDIT:
I have also tried formatting the JSON with something like this, but it just prints the brackets:
function getLog(){
$text = file('../../../home/shares/flower_hum/humid.log');
$textRemoved ="["; //Add opening bracket.
$textRemoved .= substr($text, 0, strlen($text)-1); (Remove last comma)
$textRemoved .="]";//Add closing bracket
$json = json_encode($textRemoved);
echo $json;
}
So I managed to solve it myself. Basicly The formatting of the textfile was wrong and as some commentors said, I don't need to encode it if I am doing it myself. What I ended up doing was in my application that generates the log file to add comma after each row. Then in my PHP I added brackets and removed the last comma.
function getLog(){
header('Content-Type: application/json');
$file = file_get_contents('../../../home/shares/flower_hum/humid.log');
$lengthOfFile = strlen($file)-2;
$subFile = substr($file, 0, $lengthOfFile);
$res ="[";
$res .= $subFile;
$res .="]";
echo $res;
}
You can't just jam two+ JSON strings togther. It's JSON, which means it HAS to be syntactically correct Javascript CODE. If you want to join two json strings together, you HAVE to decode them to a native data structure, join those structures together, then re-encode the new merged structure:
$temp1 = json_decode('{"foo":"bar"}', true);
$temp2 = json_decode('{"baz":"qux"}', true);
$new = array_merge($temp1, $temp2);
echo json_encode($new);
which will produce:
{"foo":"bar","baz":"qux"}
and remain valid JSON/Javascript.
Why? Consider that bare integers are valid json:
json_encode(42) -> 42
json_encode(123) -> 123
If you have two json-encoded integers and jam together, you get a "new" integer:
42123
and on the receiving end, you'll be going "Ok, so where is the split between the two", because 4 and 2123 are just as valid as possible original values as 4212 and 3.
Sending the two integers as distinct and SEPARATABLE values would require an array:
[42,123]

Trouble Reading json Data from hasoffer API

Trying to read json Data and I can't get it to work correctly with the following code:
$apiurl = "https://api.hasoffers.com/Apiv3/json?NetworkId=REDACTED&Target=Affiliate_Report&Method=getStats&api_key=REDACTED&fields%5B%5D=Stat.conversions&fields%5B%5D=Stat.unique_clicks&fields%5B%5D=Stat.payout&filters%5BStat.date%5D%5Bconditional%5D=LESS_THAN&filters%5BStat.date%5D%5Bvalues%5D=2016-02-21&filters%5BStat.date%5D%5Bconditional%5D=GREATER_THAN&filters%5BStat.date%5D%5Bvalues%5D=2016-02-21";
$data = json_decode(file_get_contents($apiurl), true);
foreach($data['response']['data'] as $dataline) {
echo "Conversions: {$dataline['Stat']['conversions']} Payout: {$dataline['Stat']['payout']}";
}
The query is generating the following json return, I just can't figure out how to read the stats correctly (it's also looping through 7 lines in the foreach which also makes no sense to me):
{"request":{"Target":"Affiliate_Report","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"REDACTED","Method":"getStats","api_key":"REDACTED","fields":["Stat.conversions","Stat.unique_clicks","Stat.payout"],"filters":{"Stat.date":{"conditional":"GREATER_THAN","values":"2016-02-21"}},"__gaTune":"GA1.2.1289716345.1455904273","__utma":"267117079.1377304869.1455903853.1455904273.1455904273.1","__utmc":"267117079","__utmz":"267117079.1455904273.1.1.utmcsr=developers.hasoffers.com|utmccn=(referral)|utmcmd=referral|utmcct=/","_biz_uid":"1742fd1f613440a4cfbb5a510d1d7def","_biz_nA":"1","_biz_pendingA":"[]","_hp2_id_1318563364":"5257773084071598.0276720083.0714677778","_ga":"GA1.2.1377304869.1455903853"},"response":{"status":1,"httpStatus":200,"data":{"page":1,"current":50,"count":1,"pageCount":1,"data":[{"Stat":{"conversions":"1000","unique_clicks":"1000","payout":"1000.000000"}}],"dbSource":"branddb"},"errors":[],"errorMessage":null}}
If your JSON is exactly that you have posted, it is unvalid JSON, as per the comments.
The invalid part is the REDACTED words without double-quote.
To bypass this error, you can try in this way:
$data = file_get_contents( $apiurl );
$data = preg_replace( '/:REDACTED(?=\W)/', ':"REDACTED"', $data );
$json = json_decode( $data, True );
This will works on example above, but please note that is a trick, and it can not work if some JSON field has a value like "sometext:REDACTED,sometext": it is improbable, but not impossible.
Actually thank you that site helped a lot realized there was a second array also labeled "data" under the first "data" array so I needed to change it to:
$data['response']['data']['data'] as $dataline

how to pass variable value in URL via file_get_contents

I want to integrate SMS to my API and try to pass the variables in URL but it says error, no number found.
Please help
$sender = "9999708993";
$reply_message = "This is an auto generated message";
echo $sender;
echo $reply_message;
$lines = file_get_contents('http://sms2.oxyzen.in/httpapi/sendsms.php?loginid=myid&password=mypassword&senderid=mysenderid&message=$reply_message&number=$sender');
echo "<pre>$lines</pre>";
use double quotes rather than single quotes if you want to put variables in:
$lines = file_get_contents("http://sms2.oxyzen.in/httpapi/sendsms.php?loginid=myid&password=mypassword&senderid=mysenderid&message=$reply_message&number=$sender");
Please try this:
$sender = "9999708993";
$reply_message = urlencode("This is an auto generated message");
//I think you need to change these
$loginid='myid';
$mypassword='mypassword';
$mysenderid='mysenderid';
$uri = "http://sms2.oxyzen.in/httpapi/sendsms.php?loginid=$myid&password=$mypassword&senderid=$mysenderid&message=$reply_message&number=$sender";
var_dump($uri);
$lines=file_get_contents($uri);
var_dump($lines);
try cleaning the URL, it might have a new line at the end
trim("$URL");

make HTML tags inside json response work

I am retrieving some data from Wikipedia using Wikipedia API as JSON. I am getting html tags along with the data as response. When displaying on browser the html tags are displayed as plain text not as the regular output(I hope I am clear with this sentence). I want to show those as how it should look instead of plain text.following is my PHP code.
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Sachin_Tendulkar&format=json&redirects&inprop=url&indexpageids';
$json = file_get_contents($url);
echo $json ;
Following is the angularJS controller which is used to display the data
var demoApp = angular.module('demoApp',[]);
demoApp.controller('SimpleController',function ($scope,$http){
$http.post('server/view1.php').success(function(data){
$scope.info = data;
});
});
In this case:
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Sachin_Tendulkar&format=json&redirects&inprop=url&indexpageids';
$jsonString = file_get_contents( $url );
$jsonDecoded = json_decode($jsonString, true );
$pageData = $jsonDecoded['query']['pages'][57570]['extract'];
echo $pageData;
You need to use the function json_decode if you want to interpret JSON data.
You must use json_decode($json) to parse response to valid php code.

Categories