I need to interpret the array received from a remote licensing.
I am calling the remote api via curl and the answer in the browser is:
The parsed answer from curl done by using:
parse_str(curl_exec($ch), $parsed);
print_r($parsed);
is exactly as here:
Array ( [{"success":true,"uses":154,"purchase":{"id":"GYFt6sW7hbURSVdSpipb5g] => =","created_at":"2015-06-06T16:44:41Z","email":"askolon11#gmail.com","full_name":"daniel","variants":"","custom_fields":[],"product_name":"Direkt 1.2","subscription_cancelled_at":null,"subscription_failed_at":null}} )
I tried already for several hours to get the "success" item so later on to check it if it is true or false.
I used
while (list($var, $val) = each($parsed)) {
print "$var is $val\n";
}
but the result is the same.
Also I tried:
$parsed[0]['success'] or $parsed[0]['success']
and no result as well.
My full code is:
<?php $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.gumroad.com/v2/licenses/verify");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array( 'product_permalink' => 'skQsA', 'license_key' => 'AB26AD9D-1B3B42E0-92356540-CF4E7C1B' );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
$output = array();
parse_str(curl_exec($ch), $parsed);
print_r($parsed); // HERE WE HAVE THE ARRAY
while (list($var, $val) = each($parsed)) {
// print "$var is $val\n";
}
curl_close($ch);
?>
Thank you.
The API seems to return a JSON encoded string. So instead of:
parse_str(curl_exec($ch), $parsed);
use:
$parsed = json_decode(curl_exec($ch), true);
Then a print_r($parsed) will output:
Array
(
[success] => 1
[uses] => 154
...
)
And for checking success value:
if ($parsed['success']) {
// Do stuff
}
Instead of doing
$parsed[0]['success'];
try just
$parsed['success'];
If the array you are getting back is an associative array, then the 'key' will be the word 'success'.
$parsed = [
"success" => true,
"uses" => 154,
"purchase" =>
[
"id" => "GYFt6sW7hbURSVdSpipb5g] => =",
"created_at" => "2015-06-06T16:44:41Z",
"email" => "askolon11#gmail.com",
"full_name" => "daniel",
"variants" => "",
"custom_fields" => [],
"product_name" => "Direkt 1.2",
"subscription_cancelled_at" => null,
"subscription_failed_at" => null
]];
if($parsed['success'])
echo 'true';
else
echo 'false';
Related
In below code, I am trying to pass values dynamically for "OrderNo & AWB".
$sql="SELECT order_id , alternateno FROM do_order";
$con=mysqli_connect("localhost","root","","do_management");
if ($result=mysqli_query($con,$sql))
{
while ($row=mysqli_fetch_row($result))
{
$data =
array (
'OrderNo' => '$row[order_id]',
'ManifestDetails' =>
array (
'AWB' => '$row[alternateno]',
'PaymentStatus' => 'COD',
),
);
}
mysqli_free_result($result);
}
mysqli_close($con);
$url = "http://1234.1234.1234.1234";
$data = json_encode($data);
$curl = curl_init($url);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
Every time when I call URL in a browser, its display below error message:
"ReturnMessage":"AWB no with same order id ($row[order_id]) already exists","AWBNo":"$row[alternateno]"
But if I give static values for OrderNo (16445) & AWB (16445), then it works fine:
"ReturnMessage":"successful","AWBNo":"16445"
So it seems I am not passing values properly, please guide me on this.
mysqli_fetch_row() generates an array of indexed arrays. Access the result set data using the column indexes [0] for order_id and [1] for alternateno. You must also remove the single quotes when storing $row[0] and $row[1] in $data.
Right now, your query will be returning a result set of n rows. your while() loop will be overwriting and overwriting and overwriting $data and only preserving the final iteration's row data.
If you want to store all of the rows' data to $data, then write $data[] to push new row-data into your $data array.
Untested Code:
if (!$con = mysqli_connect("localhost", "root", "", "do_management")) {
echo "connection error";
} elseif (!$result = mysqli_query($con, "SELECT order_id, alternateno FROM do_order")) {
echo "query error";
} else {
$url = "http://114.143.206.69:803/StandardForwardStagingService.svc/AddManifestDetails";
while ($row = mysqli_fetch_row($result)) { // fetch_row does not generate associative keys
$data = [
'OrderNo' => $row[0],
'ManifestDetails' => ['AWB' => $row[1], 'PaymentStatus' => 'COD']
];
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_VERBOSE, true);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
}
mysqli_free_result($result);
}
Remove the quotes of order_id and alternateno and try it
<?php
$sql="SELECT order_id , alternateno FROM do_order";
$con=mysqli_connect("localhost","root","","do_management");
if ($result=mysqli_query($con,$sql))
{
while ($row=mysqli_fetch_row($result))
{
$data =
array (
'OrderNo' => $row['order_id'],
'ManifestDetails' =>
array (
'AWB' => $row['alternateno'],
'PaymentStatus' => 'COD',
),
);
}
mysqli_free_result($result);
}
mysqli_close($con);
?>
You need to change :
array (
'OrderNo' => '$row[order_id]',
'ManifestDetails' =>
array (
'AWB' => '$row[alternateno]',
'PaymentStatus' => 'COD',
),
);
To
array (
'OrderNo' => $row['order_id'],
'ManifestDetails' =>
array (
'AWB' => $row['alternateno'],
'PaymentStatus' => 'COD',
),
);
So here is the issue. I am pulling a CSV file from an API and need to place it into an array. Here is my current code:
$url = "https://www.*****************";
$myvars = 'username=*********&password=*************';
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text'));
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(!curl_exec($ch)){
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
} else {
$response = curl_exec($ch);
$exploded = nl2br($response);
//echo $response."<br>";
var_dump($exploded);
}
curl_close($ch);
The problem is I am getting the response:
string(245) ""Number","Name","Description","Type","Fixed Width Boolean","Quote Character","Delimiter Character","End of Line Sequence","Header Boolean","Column Count"
"1","All Calls","All Call Data","Call","false","None",",","\r\n","true","14"
"
This is two lines in the CSV, but comes out in a single string line. I tried exploding it, but it seems to have two delimiters and I tried splitting it, but it will not find the second delimiter. I want it to generate like this:
array(
"Number" => 1,
"Name" => "All Calls",
"Description" => "All Call Data",
"Type" => "Call",
"Fixed Width Boolean" => false,
"Quote Character" => "None",
"Delimiter Character" => ",",
"End of Line Sequence" => "\r\n",
"Header Boolean" => true,
"Column Count" => 14
);
The first line of the CSV is the headers and the data underneath is the data it needs to align to. Also future requests will have multiple lines of data and they need to match with the headers too. Any ideas?
If you're dealing with CSV, try using the built-in function for such. Then use array_combine to stick your headers in as keys:
$response = curl_exec($ch);
$csv_data = array_map('str_getcsv', explode("\n", $response));
$headers = array_shift($csv_data);
foreach ($csv_data as $v) {
$data[] = array_combine($headers, $v);
}
As an example:
$response = <<< CSV
"Number","Name","Description","Type","Fixed Width Boolean","Quote Character","Delimiter Character","End of Line Sequence","Header Boolean","Column Count"
"1","All Calls","All Call Data","Call","false","None",",","\\r\\n","true","14"
CSV;
$csv_data = array_map('str_getcsv', explode("\n", $response));
$headers = array_shift($csv_data);
foreach ($csv_data as $v) {
$data[] = array_combine($headers, $v);
}
print_r($data);
Output:
Array
(
[0] => Array
(
[Number] => 1
[Name] => All Calls
[Description] => All Call Data
[Type] => Call
[Fixed Width Boolean] => false
[Quote Character] => None
[Delimiter Character] => ,
[End of Line Sequence] => \r\n
[Header Boolean] => true
[Column Count] => 14
)
)
You can also turn your csv string into a file pointer and use fgetcsv on it. Here is an example of how it works:
Josh:~$ php -a
Interactive shell
php > $data = <<<CSV
<<< > "col1","col2"
<<< > "d1",","
<<< > CSV;
php > echo $data;
"col1","col2"
"d1",","
php > $fp = fopen('data://text/plain,' . $data, 'r');
php > while (($row = fgetcsv($fp)) !== false) {
php { var_dump($row);
php { }
array(2) {
[0]=>
string(4) "col1"
[1]=>
string(4) "col2"
}
array(2) {
[0]=>
string(2) "d1"
[1]=>
string(1) ","
}
Using your example it would be similar to the following
$response = <<<CSV
"Number","Name","Description","Type","Fixed Width Boolean","Quote Character","Delimiter Character","End of Line Sequence","Header Boolean","Column Count"
"1","All Calls","All Call Data","Call","false","None",",","\r\n","true","14"
CSV;
$fp = fopen('data://text/plain,' . $response, 'r');
$data = [];
$header = fgetcsv($fp); // first row is column headers
while (($row = fgetcsv($fp)) !== false) {
$data[] = array_combine($header, $row);
}
print_r($data); // list of rows with keys set to column names from $header
/*
Array
(
[0] => Array
(
[Number] => 1
[Name] => All Calls
[Description] => All Call Data
[Type] => Call
[Fixed Width Boolean] => false
[Quote Character] => None
[Delimiter Character] => ,
[End of Line Sequence] =>
[Header Boolean] => true
[Column Count] => 14
)
)
*/
Well, this is a bit "hacky" but it works....
PHP Fiddle
$response = '"Number","Name","Description","Type","Fixed Width Boolean","Quote Character","Delimiter Character","End of Line Sequence","Header Boolean","Column Count","1","All Calls","All Call Data","Call","false","None",",","\r\n","true","14"';
$response = preg_replace('/[,]/', "*", $response);
$response = str_replace('*"*"*', '*","*', $response);
$exploded = explode("*", $response);
$count = count($exploded)/2;
$newArray = [];
for($i=0; $i<$count; ++$i){
$newArray[$exploded[$i]] = $exploded[$i+$count];
}
print_r($newArray);
Which prints
Array
(
["Number"] => "1"
["Name"] => "All Calls"
["Description"] => "All Call Data"
["Type"] => "Call"
["Fixed Width Boolean"] => "false"
["Quote Character"] => "None"
["Delimiter Character"] => ","
["End of Line Sequence"] => "\r\n"
["Header Boolean"] => "true"
["Column Count"] => "14"
)
Below is my code, I am trying to get particular api response (msg,amt) in php string.
........................................................................................................................................
$key = "XXXXX";
$mykey = "XXXXX";
$command = "Check";
$value = "5454355435";
$r = array('key' => $key , 'value' => $value, 'command' => $command);
$qs= http_build_query($r);
$wsUrl = "https://info.service-provider.com";
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $wsUrl);
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, $qs);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
$o = curl_exec($c);
if (curl_errno($c)) {
$sad = curl_error($c);
throw new Exception($sad);
}
curl_close($c);
$valueSerialized = #unserialize($o);
if($o === 'b:0;' || $valueSerialized !== false) {
print_r($valueSerialized);
}
print_r($o);
RESPONSE:
{"status":1,"msg":"1 out of 1 Transactions Fetched Successfully","transaction_details":{"2767712494": {"mihpayid":"268999084","request_id":"","ref_num":"020814301298","amt":"1.00","txnid":"5454355435","additional_charges":"0.00","productinfo":"SHIRT"}}}
Your string is in json format. To get value from it, you should convert it into an array like this:
$json = '{"status":1,"msg":"1 out of 1 Transactions Fetched Successfully","transaction_details":{"2767712494": {"mihpayid":"268999084","request_id":"","ref_num":"020814301298","amt":"1.00","txnid":"5454355435","additional_charges":"0.00","productinfo":"SHIRT"}}}';
$array = json_decode($json, true);
echo '<pre>'; print_r($array);
Your array will look like this:
Array
(
[status] => 1
[msg] => 1 out of 1 Transactions Fetched Successfully
[transaction_details] => Array
(
[2767712494] => Array
(
[mihpayid] => 268999084
[request_id] =>
[ref_num] => 020814301298
[amt] => 1.00
[txnid] => 5454355435
[additional_charges] => 0.00
[productinfo] => SHIRT
)
)
)
To get msg you should write like this:
echo $array['msg'];
You can get more information from json_decode
Let me know for more help.
This response looks like JSON format.
Pass this response string to php method json_decode like:
$response = json_decode($yourResponseString,true);
and then you should be able to access it's properties like a regular associative array:
$msg = $response['msg'];
I'm working on a project and trying to find a way to add my api results to mysql.
Here is the page were you can find the results.
Here is the code of the page:
<?php
///PLOT PROJECT USER REQUEST
//HELPER FUNCTION TO PRINT TO CONSOLE
function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}
//PLOT PROJECT REQUEST
$appId = '9fed0c75ca624e86a411b48ab27b3d5a';
$private_token = 'VGjPehPNBa5henSa';
$qry_str = "/api/v1/account/";
$ch = curl_init();
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode($appId.":".$private_token) // <---
);
$geofenceId = '736cb24a1dae442e943f2edcf353ccc7';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, 'https://admin.plotprojects.com/api/v1/notification/?geofenceId=' . $geofenceId);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
$content = trim(curl_exec($ch));
curl_close($ch);
print $content;
?>
You can use json_decode() to decode your JSON string and take the values that you need to make your query. Read more at:
http://php.net/manual/en/function.json-decode.php
<?php
//The response from http://www.jobsinsac.com/api/api_notification.php
$json = '{ "success": true, "result": { "data": [{ "placeId": "736cb24a1dae442e943f2edcf353ccc7", "cooldownDays": 0, "triggerTimes": "inherit", "state": "published", "cooldownSeconds": 1, "data": "http://www.illuminatimc.com", "enabled": true, "geofenceId": "736cb24a1dae442e943f2edcf353ccc7", "id": "0cad6b54d225459e85cd8c27567f8b0b", "message": "Get a cold beer, for $2.00, shots for $4.00, come inside, up stairs.", "created": "2015-03-17T18:54:41Z", "timespans": [], "handlerType": "landingPage", "trigger": "enter" }], "total": 1 } }';
$data = json_decode($json, true);
print_r($data);
?>
Output:
Array
(
[success] => 1
[result] => Array
(
[data] => Array
(
[0] => Array
(
[placeId] => 736cb24a1dae442e943f2edcf353ccc7
[cooldownDays] => 0
[triggerTimes] => inherit
[state] => published
[cooldownSeconds] => 1
[data] => http://www.illuminatimc.com
[enabled] => 1
[geofenceId] => 736cb24a1dae442e943f2edcf353ccc7
[id] => 0cad6b54d225459e85cd8c27567f8b0b
[message] => Get a cold beer, for $2.00, shots for $4.00, come inside, up stairs.
[created] => 2015-03-17T18:54:41Z
[timespans] => Array
(
)
[handlerType] => landingPage
[trigger] => enter
)
)
[total] => 1
)
)
I need to output an array with a specif format from a cURL request. I tried many ways to format the XML result as needed without luck.
Here's the PHP code
<?php
$request_url = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?nCdEmpresa=&sDsSenha=&sCepOrigem=71939360&sCepDestino=72151613&nVlPeso=1&nCdFormato=1&nVlComprimento=16&nVlAltura=5&nVlLargura=15&sCdMaoPropria=s&nVlValorDeclarado=200&sCdAvisoRecebimento=n&nCdServico=41106%2C40045&nVlDiametro=0&StrRetorno=xml 4110616,9034,000,001,50SN04004519,2014,000,002,00SS0";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_TIMEOUT, 130);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
print_r($response);
?>
It prints the following XML
<servicos>
<cservico>
<codigo>41106</codigo>
<valor>16,90</valor>
<prazoentrega>3</prazoentrega>
...
<erro>0</erro>
<msgerro>
</msgerro>
</cservico>
<cservico>
<codigo>40045</codigo>
<valor>19,20</valor>
<prazoentrega>1</prazoentrega>
...
<erro>0</erro>
<msgerro>
</msgerro>
</cservico>
</servicos>
Or the following array if I apply $xml = new SimpleXMLElement($response);
SimpleXMLElement Object
(
[cServico] => Array
(
[0] => SimpleXMLElement Object
(
[Codigo] => 41106
[Valor] => 16,90
[PrazoEntrega] => 3
...
[Erro] => 0
[MsgErro] => SimpleXMLElement Object
(
)
)
[1] => SimpleXMLElement Object
(
[Codigo] => 40045
[Valor] => 19,20
[PrazoEntrega] => 1
...
[Erro] => 0
[MsgErro] => SimpleXMLElement Object
(
)
)
)
)
What I need to return is and Array like this. I tried almost every method found in other questions here but never got a good way to construct this two-dimension array.
array(
'Option Name' => array(
'id'=>'40045',
'quote'=>'20,20',
'days'=>'1',
),
'Option Name' => array(
'id'=>'40215',
'quote'=>'29,27',
'days'=>'3',
)
)
*Option Name will be retrieved afterwards by ID code.
This should work flawlessly!
$xml = simplexml_load_string($response);
$json = json_encode($xml);
$arr = json_decode($json,true);
$temp = array();
foreach($arr as $k=>$v) {
foreach($v as $k1=>$v1) {
$temp[$k][$k1] = $v1;
}
}
echo "<pre>";print_r($temp);echo "</pre>";
http://ka.lpe.sh/2012/07/26/php-convert-xml-to-json-to-array-in-an-easy-way/
Try this function (pass the response to it and it should return you your array) :
function getArrayFromResponse($response) {
$xml = new SimpleXMLElement($response);
$array = array();
foreach($xml->cServico as $node){
$array[] = array(
'id' => $node->Codigo,
'quote' => $node->Valor,
'days' => $node->PrazoEntrega
);
}
return $array;
}
$ch = curl_init();
$sendurl = "http://example.com";
curl_setopt($ch, CURLOPT_URL, $sendurl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $data);
$xml = new \SimpleXMLElement($response);
$array = json_decode(json_encode((array)$xml), TRUE);
echo "<pre>";
print_r($array);
Working charming for me.
I finally got it. After testing all your suggestions and many others found on google, I came up with this:
<?php
$request_url = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?nCdEmpresa=&sDsSenha=&sCepOrigem=71939360&sCepDestino=72151613&nVlPeso=1&nCdFormato=1&nVlComprimento=16&nVlAltura=5&nVlLargura=15&sCdMaoPropria=s&nVlValorDeclarado=200&sCdAvisoRecebimento=n&nCdServico=41106%2C40045&nVlDiametro=0&StrRetorno=xml 4110616,9034,000,001,50SN04004519,2014,000,002,00SS0";
//Setup cURL Request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_TIMEOUT, 130);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
$xml = simplexml_load_string($response);
$services = $xml->cServico;
$result = array();
foreach($services as $service) {
$id = $service->Codigo->__toString();
$quote = $service->Valor->__toString();
$delivery_days = $service->PrazoEntrega->__toString();
//Get simplified service name (option_name)
switch ($id) {
case "40010":
case "40096":
case "40436":
case "40444":
case "40568":
case "40606":
$option_name = 'SEDEX'; break;
case "81019":
case "81868":
case "81833":
case "81850":
$option_name = 'e-SEDEX'; break;
case "41106":
case "41068":
$option_name = 'PAC'; break;
case "40045":
case "40126":
$option_name = 'SEDEX a Cobrar'; break;
case "40215":
$option_name = 'SEDEX 10'; break;
case "40290":
$option_name = 'SEDEX Hoje'; break;
case "81027":
$option_name = 'e-SEDEX Prioritário'; break;
case "81035":
$option_name = 'e-SEDEX Express'; break;
}
$result[$option_name] = array('id' => $id, 'quote' => $quote, 'delivery_days' => $delivery_days);
}
?>
The final secret was to add __toString() to convert values returned as array to a simple string. It prints perfectly. Thank you guys!!
Array
(
[PAC] => Array
(
[id] => 41106
[quote] => 16,90
[delivery_days] => 3
)
[SEDEX a Cobrar] => Array
(
[id] => 40045
[quote] => 19,20
[delivery_days] => 1
)
)