Trouble Reading json Data from hasoffer API - php

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

Related

PHP function to call JSON files

I am trying to make a basic PHP function in order to call json files repeatedly throughout the app. Every time I want to call a json file I use:
<? $site = json_decode(file_get_contents('views/partials/site.json')); ?>
Then I use echo to use data from json file like this:
<? echo $site[0]->title; ?>
But instead of repeating part one I want to write a function in the header and call it where I want to call a json file. After that i was planning to use the function like this:
$site = jsonCall('site');
by using the function below;
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
echo $jsonCalled;
};
but instead of what i want i got an array as a response from server. i think my function turns json file to an array and that way i can't call it properly.
anyone knows how to solve this simple issue? show me proper way to write this function so my code might look a bit easier to read. Thank you.
by changing echo in function with return and using jsonCall('site')[0]->title; everything worked fine.
Of course you are getting an array. Otherwise $site[0] (which is an array access at key zero) would not have worked.
From the PHP docs (http://php.net/manual/en/function.json-decode.php):
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
Your appropriate PHP type is array.
The following should work:
jsonCall('site')[0]->title;
Therefore I can not see a problem with your code?
The server is responding with Array because that is how PHP represents an array when you are echo'ing it. Your function should be returning the result.
Try:
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
// echo $jsonCalled;
return $jsonCalled; // <- this should work
};

file_get_contents with Variable

Hey so I'm having a slight dilemma with getting the contents of a file using a variable.
So to explain the code below a little, the respform fetches JSON array all ok. And the results url when echo'd displays like a normal URL that when viewed displays JSON data. Then I want to fetch JSON data from the second URL. If I use this variable in file_get_contents nothing happens. If I simply create a variable $url = '' and type the same address it works fine.
I've var dumped the $resulturl variable that I'm using and it is a string(56). I've tried using json_encode and it becomes a string(64). What sort of data does it need to be to be accepted into the file_get_contents.
$resp = file_get_contents($url, FALSE, $context);
$respform = json_decode($resp, TRUE);
$resulturl = $respform['resultsUrl'];
$data = file_get_contents($resulturl, FALSE);
$insta_array = json_decode($data, TRUE);
print_r($insta_array);
Hope someone can help, Thanks!
$resulturl apparently contains a JSON-encoded URL. You need to do:
$resulturl = json_decode($respform['resultsUrl']);

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.

Cannot Parse Paypal "notify_url" Data Into an Associative Array (PHP)

I am setting up a Paypal sandbox. Everything works fine. When the transaction is done, paypal POSTS some data to my "notify_url" page (which I've named process-payment.php).
Now, when I post:
$array = $_POST;
$encodedString = json_decode($array);
Now, I can PUT that encoded string in the database, and it looks like:
{"mc_gross":"10.00","protection_eligibility":"Eligible",
"address_status":"confirmed","payer_id"}
Now, my big question is, how can I get THAT (^^^) into an associative array, where I can store those values in a database that records the transaction? Thank you so much for your help in advance! I've already tried:
$pp_array = file_get_contents('php://input');
$arrayDump = json_encode($pp_array);
$pp_array = json_decode($pp_array, true);
Which, obviously, didn't work. So, kinda hoping someone can give me a little tutelage here!
You are trying to use json_decode on an bad array because your payer_id is NULL. Consider filling or removing it. This is a working example with a filled payer_id:
$json = '{"mc_gross":"10.00","protection_eligibility":"Eligible", "address_status":"confirmed","payer_id":"2"}';
$json_asoc = (json_decode($json, true));
print $json_asoc['mc_gross']; // 10
For details see here
So, turns out that the code I used to make it work was this:
$array = $_POST;
$arrayDump = json_encode($array);
file_put_contents('payment-record.txt', $arrayDump);
$fileContents = file_get_contents('payment-record.txt');
$pp_array = json_decode($fileContents, true);
That gave me a workable array. Not sure why I had to write it first, but there you go.

Part of string missing after urldecode() in php

I have an encoded string (it is too long to be posted here). When I use different utilities for decoding the string (http://www.the-art-of-web.com/javascript/escape/) the string looks perfect after urldecode(). However, when I actually pass the string through urldecode() in my php file on my testing environment the first 100 or so characters are missing. I cannot figure out why. I have tried both urldecode and rawurldecode. If you want to see the string I am trying to process you can make a GET request against this url http://pacific-wave-7885.herokuapp.com/api/opencart the string I am working with is the "contents" value of the JSON object
What i am trying to accomplish:
I want to make a php file that calls the above api address, gets the contents from the JSON object, decodes the string and parses the code.
here is what I have tried:
function utf8_urldecode($str) {
$str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str));
return html_entity_decode($str,null,'UTF-8');;
}
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
$file = file_get_contents('http://pacific-wave-7885.herokuapp.com/api/opencart', false, $context);
$contents_decode = utf8_urldecode($file);
echo $contents_decode;
You can see with this code that the "contents" starts with "language->load('shipping/usps')" and is missing the first 100 or so characters of that part of the string.
I have also tried this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://pacific-wave-7885.herokuapp.com/api/opencart");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$data = json_decode($output, true);
$contents = $data[0]['contents'];
$contents_decode = urldecode($contents);
echo $contents_decode;
curl_close($ch);
This also produces the same result - part of the beginning of the string is missing.
to reiterate: if you grab the encoded string straight from the JSON object and use an online decoding tool the string looks great, but once it is passed through urldecode() in my php file the first part of the string is missing characters.
If anyone can see what I am missing I would be so grateful.
Just fyi: My php environment is the latest version of XAMPP with php5 and the JSON object is coming from a NODE server with express.js.
If anyone has a better idea of how I can pass php code as a string from a Node server to a PHP server and then parse it I would be open to that as well.
I'm going to make two assumptions:
It's showing up starting at language->load('shipping/usps');
You are viewing the returned string in your browser.
Good news is that you aren't missing any characters! The browser is simply misinterpreting the tags -
<?php
class ModelShippingUsps extends Model {
public function getQuote($address) {
$this->
The browser is trying to make sense of it - it doesn't know this is PHP, it thinks it is HTML. It sees < and thinks "oh cool, beginning of an HTML tag." And then it sees ? and it just tries to figure out what kind of malformed tag this is, and then it see's -> and it decides it must be an HTML comment, so it parses it as:
<!--?php
class ModelShippingUsps extends Model {
public function getQuote($address) {
$this--->
Change echo $contents_decode; to echo "<textarea>" . $contents_decode . "</textarea>" and you'll see the full string.
Why not just return the data (instead of a PHP block in the contents) and have your PHP class on the receiving end decode the JSON and complete the logic.
If you are insisting on getting the PHP block back...it might be easier to just return a JSON response from node/express and use json_decode to pull it into an array. In playing with this the only way I could make your PHP block JSON friendly was to escape it then encodeURIComponent.
<?php
$jsonString = '{
"name":"usps.php",
"version":1,
"platform":"opencart",
"contents":"%253C%253Fphp%250Aclass%2520ModelShippingUsps%2520extends...57D%250A%2509%2509%257D%250A%250A%2509%2509return%2520%2524method_data%253B%250A%2509%257D%250A%257D%250A%253F%253E",
"_id":"53c40942bddf820200000007",
"__v":0
}
';
$jsonArr = json_decode( $jsonString, true);
var_dump( urldecode( urldecode( $jsonArr["contents"] ) ) );
?>

Categories