<?php
error_reporting(E_ALL);
$ch = curl_init();
ini_set('max_execution_time', 0); ini_set('set_time_limit', 0);
curl_setopt($ch, CURLOPT_URL, "https://security.voluum.com/login");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$headers = array();
$headers[] = "Authorization: Basic username:password";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
$res_decoded = json_decode($result);
$tok = $res_decoded->token;
$id = 'asdafewfcs';
$karon = date("Y-m-d");
$datetime = new DateTime('tomorrow');
$sh = curl_init();
curl_setopt($sh, CURLOPT_URL, "https://portal.voluum.com/report?from=" .$karon. "T00:00:00Z&to=" . $datetime->format('Y-m-d') . "T00:00:00Z&tz=Etc%2FGMT&sort=revenue&direction=desc&columns=offerName&columns=visits&columns=clicks&columns=conversions&columns=revenue&columns=cost&columns=profit&columns=cpv&columns=ctr&columns=cr&columns=cv&columns=roi&columns=epv&columns=epc&columns=ap&columns=affiliateNetworkName&groupBy=offer&offset=0&limit=100&include=active&filter1=campaign&filter1Value=" . $id);
curl_setopt($sh, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($sh, CURLOPT_CUSTOMREQUEST, "GET");
$header = array();
$header[] = "Cwauth-Token: " . $tok;
curl_setopt($sh, CURLOPT_HTTPHEADER, $header);
$results = curl_exec($sh);
if (curl_errno($sh)) {
echo 'Error:' . curl_error($sh);
}
$user = json_decode($results, true);
echo '<pre>' . print_r($user, TRUE) . '</pre>';
foreach($user['rows'] as $mydata)
{
$visit = $mydata['visits'] ;
echo $visit . "\n<br>";
if($visit >= 10){
$wh = curl_init();
curl_setopt($wh, CURLOPT_URL, "https://core.voluum.com/campaigns/" . $id);
curl_setopt($wh, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($wh, CURLOPT_CUSTOMREQUEST, "GET");
$head = array();
$head[] = "Cwauth-Token: " . $tok;
curl_setopt($wh, CURLOPT_HTTPHEADER, $head);
$resulta = curl_exec($wh);
if (curl_errno($wh)) {
echo 'Error:' . curl_error($wh);
}
echo "Request:" . "<br>";
$campinfo = json_decode($resulta, true);
echo '<pre>' . print_r($campinfo, TRUE) . '</pre>';
foreach($campinfo['pathsGroups'] as $datacamp){
echo $datacamp['active'];
$xh = curl_init();//starts not working when i add codes from here to end
curl_setopt($xh, CURLOPT_URL, "https://core.voluum.com/campaigns/" . $id);
curl_setopt($xh, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($xh, CURLOPT_POSTFIELDS,http_build_query(array($datacamp['active']),'','&');
curl_setopt($xh, CURLOPT_CUSTOMREQUEST, "PUT");
$header = array();
$header[] = "Cwauth-Token: " . $tok;
curl_setopt($xh, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($xh);
if (curl_errno($xh)) {
echo 'Error:' . curl_error($xh);
}
}
}
}
curl_close ($ch);
curl_close ($sh);
curl_close ($wh);
curl_close ($xh);
?>
can someone please check my syntax i don't know whats wrong with it when i run it it says page isn’t workinq. ive already have ini_set('max_execution_time', 0); ini_set('set_time_limit', 0); in my code but there are no error message everything was running well until i add the PUT as what ive mentioned in the comment iam trying to replace value of [active] => false
here is a short the structure of data:
Array
(
[pathsGroups] => Array
(
[0] => Array
(
[paths] => Array
(
[0] => Array
(
[weight] => 100
[active] => 1
[landers] => Array
(
[0] => Array
(
[lander] => Array
(
[id] =>
[namePostfix] =>
[name] =>
)
[weight] => 100
)
)
[offers] => Array
(
[0] => Array
(
[offer] => Array
(
[id] =>
[name] =>
[namePostfix] =>
)
[weight] => 100
)
)
)
)
[active] => 1 //this is what i'am trying to replace
)
)
)
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',
),
);
I want to know how to get WHMCS Price via WHMCS API.
I have created a little script to get price via API which is working fine but when I update the script on my external WHMCS pages it is taking a lot more time to update the function on each page my simple question is to get price via API without defining the first array see example below.
Array
(
[result] => success
[totalresults] => xxx
[products] => Array
(
[product] => Array
(
[0] => Array // how can I call it dynamically
(
[pid] => 1
[gid] => 1
[type] => hostingaccount
[name] => Plan Name
[description] => Plan Description
[module] => cpanel
[paytype] => recurring
[pricing] => Array
(
[USD] => Array
(
[prefix] => $
[suffix] => USD
[msetupfee] => 0.00
[qsetupfee] => 0.00
[ssetupfee] => 0.00
[asetupfee] => 0.00
[bsetupfee] => 0.00
[tsetupfee] => 0.00
[monthly] => 0.14
[quarterly] => 0.39
[semiannually] => 0.73
[annually] => 1.32
[biennially] => 2.39
[triennially] => 3.20
)
)
)
)
)
)
I just want to get price after I define [pid] and then I will create a function like
GetPrice($pid, $billingcycle); // to get produce price according to tenure
My Script:
$identifier = "IDENTIFIER";
$secret = "SECRET";
$APIURL = "mydomain/whmcs_directory/includes/api.php"; // it is with HTTPS
$postfields = array(
'username' => $identifier,
'password' => $secret,
'action' => 'GetProducts',
'responsetype' => 'json',
);
// Call the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $APIURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
$response = curl_exec($ch);
if (curl_error($ch)) {
die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch));
}
curl_close($ch);
// Decode response
$jsonData = json_decode($response, true);
and then I want to use function to get price according product id & tenure as defined earlier but complete function looks like this.
function GetPrice($pid, $billingcycle){
// $pid will be product ID
// $billingcycle will be 1,3,6,12,24,36 accordingly.
/**
* It would be great if I could just remove "["products"]["product"]"
* But I understand to call API I have define them so it's Okay.
*/
$monthly = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["monthly"];
$quarterly = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["quarterly"];
$semiannually = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["semiannually"];
$annually = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["annually"];
$biennially = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["biennially"];
$triennially = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["triennially"];
if( $billingcycle == "1" ){
echo $monthly;
}
if( $billingcycle == "3" ){
echo $quarterly;
}
if( $billingcycle == "6" ){
echo $semiannually;
}
if( $billingcycle == "12" ){
echo $annually;
}
if( $billingcycle == "24" ){
echo $biennially;
}
if( $billingcycle == "36" ){
echo $triennially;
}
}
I got help from WHMCS API Reference
This has done with php, please improve my code if require.
I have achieved this with the following code which work dynamically and works with product id.
PHP Function
function GetPrice($product_id, $billingcycle){
$identifier = "WHMCS_IDENTIFIER";
$secret = "WHMCS_SECRET";
$APIURL = "YOURDOMAIN.com/WHMCS_DIRECTORY/includes/api.php"; // use HTTPS
$postfields = array(
'username' => $identifier,
'password' => $secret,
'action' => 'GetProducts',
'pid' => $product_id, // Product id
'responsetype' => 'json',
);
// Call the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $APIURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); // SET to 0 for non SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
$response = curl_exec($ch);
if (curl_error($ch)) {
//die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch));
die("Out of Stock");
}
curl_close($ch);
// Decode response
$jsonData = json_decode($response, true);
$monthly = $jsonData["products"]["product"][0]["pricing"]["USD"]["monthly"];
$quarterly = $jsonData["products"]["product"][0]["pricing"]["USD"]["quarterly"];
$semiannually = $jsonData["products"]["product"][0]["pricing"]["USD"]["semiannually"];
$annually = $jsonData["products"]["product"][0]["pricing"]["USD"]["annually"];
$biennially = $jsonData["products"]["product"][0]["pricing"]["USD"]["biennially"];
$triennially = $jsonData["products"]["product"][0]["pricing"]["USD"]["triennially"];
if( $billingcycle == "1" ){
echo round( str_replace('.00', '', $monthly), 2 );
}
if( $billingcycle == "3" ){
echo round( str_replace('.00', '', $quarterly) / 3, 2 );
}
if( $billingcycle == "6" ){
echo round( str_replace('.00', '', $semiannually) / 6, 2 );
}
if( $billingcycle == "12" ){
echo round( str_replace('.00', '', $annually) / 12, 2 );
}
if( $billingcycle == "24" ){
echo round( str_replace('.00', '', $biennially) / 24, 2 );
}
if( $billingcycle == "36" ){
echo round( str_replace('.00', '', $triennially) / 36, 2 );
}
}
Using Function
echo GetPrice( 1 , 1 );
Output
1.99
I want to send complex Post data with Curl.
The data i try to send:
Array
(
[test] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[file] => CURLFile Object
(
[name] => H:\wwwroot\curl/upload.txt
[mime] =>
[postname] =>
)
)
I need to use the variables in the post-side as $_POST["test"] and $_FILES["file"]
But i can not realize that. For the (sometimes multidimensional) array-data i need http_build_query but that breaks the file. If i don`t use http_build_query my array gives an "array to string conversion" error.
How can i get this to work?
Code:
Index.php
$curl = curl_init();
$postValues = Array("test" => Array(1,2,3));
$postValues["file"] = new CurlFile(dirname(__FILE__). "/upload.txt");
curl_setopt($curl, CURLOPT_URL, "localhost/curl/post.php");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postValues);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$curlResult = curl_exec($curl);
$curlStatus = curl_getinfo($curl);
echo $curlResult;
post.php
print_r($_REQUEST);
print_r($_FILES);
After very long research to manage the same problem, I think that a simpler solution could be:
$postValues = Array("test[0]" => 1, "test[1]" => 2, "test[2]" => 3);
this is the right way to emulate what happen on browsers
<input type="hidden" name="test[0]" value="1">
<input type="hidden" name="test[1]" value="2">
...
The result is:
Array
(
[test] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
Array
(
[file] => Array
(
[name] => upload.txt
[type] => application/octet-stream
[tmp_name] => /tmp/phprRGsPU
[error] => 0
[size] => 30
)
)
After long research and testing i`ve got the (not very nice but working) solution:
function createHttpHeader($postValues, $overrideKey = null) {
global $delimiter;
// invalid characters for "name" and "filename"
$disallow = array("\0", "\"", "\r", "\n");
$data = Array();
if (!is_array($postValues)) {
$postValues = Array($postValues);
}
foreach($postValues as $key => $value) {
$useKey = $overrideKey === null ? $key : $overrideKey. "[$key]";
$useKey = str_replace($disallow, "_", $useKey);
if (is_array($value)) {
$data = array_merge($data, addPostData($value, $useKey));
} else {
$data[] = "--". $delimiter. "\r\n";
$data[] = "Content-Disposition: form-data; name=\"". $useKey. "\"";
if (is_a($value, "\CurlFile")) {
$data[] = "; filename=\"". basename($value->name). "\"\r\n";
$data[] = "Content-Type: application/octet-stream\r\n\r\n";
$data[] = file_get_contents($value->name). "\r\n";
} else {
$data[] = "\r\n\r\n". $value. "\r\n";
}
}
}
return $data;
}
Test with:
$postValues = Array(
"blaat" => 1,
"test" => Array(1,2,3),
"grid" => Array(0 => array(1,2), 1 => array(4,5)),
"gridComplex" => Array("rows" => array(1,2), "columns" => array(0 => array(1,2,3,4), 1 => array(4,5,4,5)))
);
$postValues["file[0]"] = new CurlFile($file, "text/plain");
$postValues["file[1]"] = new CurlFile($file, "text/plain");
// print_r(new CurlFile($file));exit;
$delimiter = "-------------" . uniqid();
$data = createHttpHeader($postValues);
$data[] = "--" . $delimiter . "--\r\n";
$data = implode("", $data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "localhost/curl/post.php");
curl_setopt($curl, CURLOPT_HTTPHEADER , array('Content-Type: multipart/form-data; boundary=' . $delimiter, 'Content-Length: ' . strlen($data)));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$curlResult = curl_exec($curl);
echo $curlResult;
Edit: addition the addPostData function:
function addPostData($postValues, $delimiter, $overrideKey = null) {
// invalid characters for "name" and "filename"
$disallow = array("\0", "\"", "\r", "\n");
$data = Array();
if (!is_array($postValues)) {
$postValues = Array($postValues);
}
foreach($postValues as $key => $value) {
$useKey = $overrideKey === null ? $key : $overrideKey. "[$key]";
$useKey = str_replace($disallow, "_", $useKey);
if (is_array($value)) {
$data = array_merge($data, $this->addPostData($value, $delimiter, $useKey));
} else {
$data[] = "--". $delimiter. "\r\n";
$data[] = "Content-Disposition: form-data; name=\"". $useKey. "\"";
if (is_a($value, "\CurlFile")) {
$data[] = "; filename=\"". basename($value->postname). "\"\r\n";
$data[] = "Content-Type: ". $value->mime. "\r\n\r\n";
$data[] = file_get_contents($value->name). "\r\n";
} else {
$data[] = "\r\n\r\n". $value. "\r\n";
}
}
}
return $data;
}
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 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
)
)