Parsing JSON using php and curl command from an API - php

I'm trying to parse the JSON information I get, using PHP, from a powershell script that uses a form on the web-page to send an API request that searches a test database and returns a set of clients and I want to eventually put these into a dynamically populated table.
The issue i'm having is that i'm not able to just print out a specified part of the JSON array onto the page
The JSON i'm getting looks like this:
[{
"id": 2,
"firstname": "Edward",
"lastname": "Franks",
"companyname": "",
"email": "EdwardFranks#mail.com",
"datecreated": "2018-10-09",
"groupid": 0,
"status": "Inactive"
},
{
"id": 1,
"firstname": "Frank",
"lastname": "Ti",
"companyname": "U Consultation",
"email": "frank#u.co.uk",
"datecreated": "2018-10-08",
"groupid": 0,
"status": "Active"
}]
We get this information by searching a name or an email address associated with the account.
HTML:
<form method ="post" action = "veeam.PHP">
<ul class="form-style-1">
<li>
<label>Name or Email <span class="required">*</span></label>
<input type="text" name="clientsearch" class="field-divided" placeholder="Enter details" />
<li>
<input type="submit" name="submit" onSubmit="invokeapi()"/>
</li>
</ul>
</form>
PHP:
function invokeapi() {
$client = $_POST["clientsearch"];
$username = 'username';
$password = 'password';
$url = 'http://apiURL/?command=Check-ClientWHMCS%20'.$client;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: 0'));
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
$output = curl_exec($ch);
curl_close($ch);
$clientlist = (array) json_decode($output, true);
print_r($clientlist);
echo $clientlist[0]["id"];
}
if(isset($_POST['clientsearch'])) {
invokeapi();
}
When I use the json_last_error command it says there's no issue with the JSON and when I use the isArray command in PHP it says that the variable IS and array so i'm quite stuck on where to go next.
I get some output on the webpage but it just prints out the entirety of the JSON result on a single line with Array ([0] => 1) at the end of it.
Any help on this issue would be massively appreciated.

You need to set CURLOPT_RETURNTRANSFER, now curl_exec() will print out the result immediatly instead of returning it as a string in other words $output will not be filled.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
Also your cast to an array with json_decode with true is not necessary.

Related

Displaying an API via curl onto a php webpage - Just cant figure it out

So I am trying to display info from a website onto my website via an API using curl.
And I am not to clued up on curl at all :(
So this is what I have to from the source website :
curl -H "IHOSTMN-API-KEY:YourIhostmnApiKeyHere" -X GET "https://ihostmn.com/api/v1/sharing/user/list_all_deposits"
And it should give this response:
{
"result": {
"deposits": [
{
"deposit_id": 36,
"share_id": 2,
"current_amount": 53.077553,
"total_deposited": 24.91567,
"total_earned": 28.146885,
"withdraw_address": "GcUgnY5fFwTv9ef8rsggdxbdQzLEUxpp4c",
"deposit_address": "GfUgnY5sFwTf9ez8rovtdxdEQzLcbxpb4c"
},
{
"deposit_id": 37,
"share_id": 5,
"current_amount": 885.9591,
"total_deposited": 521.92,
"total_earned": 472.30566,
"withdraw_address": "gHWHPs21H8UsSNcbfWxvn5XssAxFkcuZYe",
"deposit_address": "g4sbWWtD3tf16Dsd8wiaJkar3zhJ82qNKP"
},
{
"deposit_id": 38,
"share_id": 6,
"current_amount": 754.5115,
"total_deposited": 548.52997,
"total_earned": 416.25214,
"withdraw_address": "LLqWFFJkNSog6VwsbPWEWE4KcXJrzB6t1K",
"deposit_address": "LW5Vbt1gEkvVQzfVcpLmidLPpcED1Yp3yu"
}
]
},
"error": ""
}
I have created my php webpage but can't make it work, this is what wrote:
curl -H "IHOSTMN-API-KEY:xxxxxxxxxxxxxxxxxxxxxxxxx" -X GET "https://ihostmn.com/api/v1/sharing/user/list_all_deposits"
$obj = json_decode($result);
echo $obj[0]->deposits;
Hopefully one of you will be able to point me in the correct direction, and thank you for taking the time to help if you can.
Mark
Try something like this
<?
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://ihostmn.com/api/v1/sharing/user/list_all_deposits');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$headers = array();
$headers[] = 'Ihostmn-Api-Key: YourIhostmnApiKeyHere';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
$obj = json_decode($result);
print_r($obj->result->deposits);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
you use [] for arrays and arrows for objects.
I cannot test the API but this should give you a headstart.
Helpful links: cURL

how to integrate mazzuma payment gateway

please i need to connect my html form to php script form payment proccessing but i don't know how to build it.
i want php to start processing the payment when the submit button is clicked
here are the sample codes
sample payload
{
"price": 1,
"network": "mtn",
"recipient_number": "026xxxxxxx",
"sender": "024xxxxxxx",
"option": "rmta",
"apikey": "",
"orderID": ""
}
sample request
<?php
$url = 'https://client.teamcyst.com/api_call.php';
$additional_headers = array(
'Content-Type: application/json'
);
$data = array(
"price"=> 1,
"network"=> "mtn",
"recipient_number"=> "026xxxxxxx",
"sender"=> "024xxxxxxx",
"option"=> "rmta",
"apikey"=> ""
);
$data = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // $data is the request payload in JSON format
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $additional_headers);
$server_output = curl_exec ($ch);
?>
sample response
{"code":1,"status":"success","id":"XXXXX"}
You just make a form with input type submit button and when you submit your form
you can access your form data with like below
if(isset($_POST['button_name']))
{
// access all form field data here
}

How do i get a data from JSON server response in PHP

I'm sending a JSON request in PHP and i get a response from the server, that looks like this:
{"success":true,"result":
{"items":
[{"woj":"łódzkie","powiat":"kutnowski","gmina":"Bedlno","kod":"99-
311","miasto":"Adamów","id":"99-311Adamów167271172700"}]},
"error":null,
"unAuthorizedRequest":false}
I want to pick a content from "woj" and "powiat" but it doesn't work.
My code looks like this:
$code = 'https://hetman.e4b.com.pl/api/services/app/kodPoczt/KodPocztInfo?
kod='.$kod;
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $code);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result1 = curl_exec($ch);
//close connection
curl_close($ch);
echo $result1;
$wynik = json_decode($result1, true);
echo $wynik['result'][0]['woj'];
show your full code... curl isnt inited in your example and return_transfer isnt set. whats the output of $result1?
anyway its
$wynik['result']['items'][0]['woj'];
$temp = '{
"success": true,
"result": {
"items": [{
"woj": "łódzkie",
"powiat": "kutnowski",
"gmina": "Bedlno",
"kod": "99-311",
"miasto": "Adamów",
"id": "99-311Adamów167271172700"
}]
},
"error": null,
"unAuthorizedRequest": false
}';
$result = json_decode($temp,true);
echo $result['result']['items'][0]['woj'];

Elasticsearch Bulk data insertion - JsonParseException[Unexpected character - Using PHP

While indexing the bulk data using PHP curl method I am getting the exception as "error":"JsonParseException[Unexpected character (':' (code 58)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: [B#14abb68; line: 1, column: 18]]","status":500}
Kindly find below code which I am using for the same and do let me know what could be wrong over here.
<?php
$ch = curl_init();
$method = "POST";
$url = "http://192.168.1.204/myindex/test/_bulk";
$qry = '
{"index":{"_index": "myindex","_type":"test"}}
{
"product_id": 1,
"title": "mobile"
}
{"index":{"_index": "myindex","_type":"test"}}
{
"product_id": 2,
"title": "laptop",
}
';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PORT, 9200);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
You are not using the correct format (and there is an additional comma at the second element).
It should be:
action_and_meta_data\n
optional_source\n
action_and_meta_data\n
optional_source\n
....
action_and_meta_data\n
optional_source\n
Extracted from the documentation of elasticsearch - bulk
So, you should add the data using the following format:
{"index":{"_index": "myindex","_type":"test"}}
{"product_id": 1,"title": "mobile"}
{"index":{"_index": "myindex","_type":"test"}}
{"product_id": 2,"title": "laptop"}

Edit json response from curl response

<?php
$json_url = "http://openexchangerates.org/api/latest.json?app_id=xxxxx&callback=angular.callbacks._0";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $json_url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$response = curl_exec($curl);
$jsonString = json_encode($response, true);
$data=json_decode($jsonString);
echo '<pre>',print_r($data),'</pre>';
$status = curl_getinfo($curl);
curl_close($curl);
The output is:
angular.callbacks._0({
"disclaimer": "xx",
"license": "xx",
"timestamp": 1368136869,
"base": "USD",
"rates": {
"AED": 3.672819,
"AFN": 53.209,
"ALL": 107.953875,
"AOA": 96.358934,
"ARS": 5.214887,
....
"XOF": 501.659003,
"XPF": 91.114876,
"ZMK": 5227.108333,
"ZMW": 5.314783,
"ZWL": 322.387247
}
})
But i need to edit this output to this one (only with three rates (AED/AFN/AOA)). So, basically edit the json response in the section of rates. How can i do that?
angular.callbacks._0({
"disclaimer": "xx",
"license": "xx",
"timestamp": 1368136869,
"base": "USD",
"rates": {
"AED": 3.672819,
"AFN": 53.209,
"AOA": 107.953875,
}
})
The $response is not in correct json format:
You must remove the unnecessary parts from it:
$jsonString= substr($response, 21, -1);
You can do:
<?php
$json_url = "http://openexchangerates.org/api/latest.json?app_id=5bf388eb6f7e40209b9418e6be44f04b&callback=angular.callbacks._0";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $json_url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$response = curl_exec($curl);
$jsonString= substr($response, 21, -1);
$data=json_decode($jsonString, true);
// Get the list of rates
$rates = $data['rates'];
$new_rates = array();
$new_rates['AED'] = $rates['AED'];
$new_rates['AFN'] = $rates['AFN'];
$new_rates['AOA'] = $rates['AOA'];
$data['rates'] = $new_rates;
echo 'angular.callbacks._0('.json_encode($data).')';
$status = curl_getinfo($curl);
curl_close($curl);
It's returning a response for jsonp. You would need that on the client side, but not the server. You might try:
http://openexchangerates.org/api/latest.json?app_id=xxxxx
(i.e. omit the callback). Otherwise take a look at their API to see if you can format the request differently to receive pure JSON back without the callback.
If you absolutely can't, then you can just strip off the bad parts:
preg_match('/{.*}/', $response, $matches);
$json = json_decode($matches[0]);
Once you have the valid JSON, it's a simple matter of unsetting:
unset($json->rates->XOF);
//etc.
You could also just write the content you need to some other object if it's easier.
You may want to take a look at the API to see if you can get only specific rates back.
Read the JSON string into a PHP mapping array with json_decode, pick only the elements you need, compose a new array with them and finally reserialize it with json_encode.
Note: this method is more robust than a regex/string based one, as it makes sense of what it's being processed, thus allowing for mutation in the structure of the JSON, as long as the elements you need are at their places.
For selecting elements, use:
$keep = array("AED", "AFN", "AOA");
$data["rates"] = array_intersect_key($data["rates"], array_flip($keep));

Categories