Php Curl send File AND array data - php

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;
}

Related

cURL to array_map with utf8_encode in PHP

I'm using a cURL request to grab data from a website and adding them to properties within a loop later. However, I'm stuck on making the data adjustable enough where I can add them directly within the objects.
I have a cURL request that I'm calling that grabbing all the content that I need as below:
public function request()
{
$resource = curl_init();
curl_setopt(
$resource,
CURLOPT_URL,
'lorem ipsum'
);
curl_setopt(
$resource,
CURLOPT_HTTPHEADER,
['API Auth']
);
curl_setopt(
$resource,
CURLOPT_REFERER,
'http://' . $_SERVER['SERVER_NAME'] . '/'
);
curl_setopt(
$resource,
CURLOPT_USERAGENT,
'F'
);
curl_setopt(
$resource,
CURLOPT_RETURNTRANSFER,
1
);
$response = json_decode(curl_exec($resource), true);
if (!curl_errno($resource)) {
$info = curl_getinfo($resource);
echo 'Took ', $info['total_time'], ' seconds to send a request to ', $info['url'], "\n";
};
return $response;
}
When I call the following execution $offices_array = $this->request(); print_r2($offices_array);, this is the return that I receive:
Array
(
[paginator] => Array
(
[total] => 131
[per_page] => 500
[current_page] => 1
[last_page] => 1
[prev_page] =>
[next_page] =>
)
[data] => Array
(
[0] => Array
(
[id] => 1
[name] => Atlanta
)
I'm using this function _csv_to_array:
private function _csv_to_array($filepath) {
$data_array = array();
if(is_readable($filepath)) {
$fp = fopen($filepath, 'r');
while(($data_item = fgetcsv($fp, 1000, "\t")) !== false) {
$data_array[] = array_map('utf8_encode', $data_item);
}
fclose($fp);
}
return $data_array;
}
to print out data as this:
Array
(
[0] => Array
(
[0] => ABU DHABI
[1] => FHI
)
How could I do something similar with the cURL request?

php curl syntax check

<?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
)
)
)

PHP curl Response string splitting

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"
)

How to echo a specific value in an array?

i am having a problem with a function that i have got online from somewhere, the issue is the function is supposed to return a specific value in an array but whenever i echo the function, it gives me a big array in the print_r style! here is the code:-
function USPSParcelRate() {
$userName = 'XXXXXXXXXXX';
$orig_zip = '10459';
//Shipping Request
$dest_zip = getshipinfo('zip_code');
foreach($_SESSION as $name=> $value){
if($value>0){
if(substr($name, 0, 5)=='cart_'){
if(substr($name, 0, 5)=='cart_'){
$id=substr($name, 5, (strlen($name)-5));
$query = mysql_query("SELECT `category`,`subcategory` FROM `items` WHERE `id`='".mysql_real_escape_string((int)$id)."' ");
while($query_row = mysql_fetch_assoc($query)){
$category = $query_row['category'];
$subcategory = $query_row['subcategory'];
}
$sql = mysql_query("SELECT `pounds`,`ounces` FROM `categories` WHERE `category`='".$category."' AND `subcategory`='".$subcategory."' ");
while($sql_row = mysql_fetch_assoc($sql)){
$pounds = $sql_row['pounds'];
$ounces = $sql_row['ounces'];
}
}
}
}
}
$url = "http://production.shippingapis.com/shippingapi.dll";
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// parameters to post
curl_setopt($ch, CURLOPT_POST, 1);
$data = "API=RateV4&XML=http://production.shippingapis.com/shippingapi.dll=<RateV4Request USERID='151ALHAD4911' >
<Revision/>
<Package ID='1ST'>
<Service>PRIORITY</Service>
<ZipOrigination>$orig_zip</ZipOrigination>
<ZipDestination>$dest_zip</ZipDestination>
<Pounds>$pounds</Pounds>
<Ounces>$ounces</Ounces>
<Container>NONRECTANGULAR</Container>
<Size>LARGE</Size>
<Width>12</Width>
<Length>15.5</Length>
<Height>6</Height>
<Girth>31</Girth>
</Package>
</RateV4Request>";
// send the POST values to USPS
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result=curl_exec ($ch);
$data = strstr($result, '<?');
// echo '<!-- '. $data. ' -->'; // Uncomment to show XML in comments
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (array_key_exists('attributes',$xml_elem)) {
list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
} else {
$level[$xml_elem['level']] = $xml_elem['tag'];
}
}
if ($xml_elem['type'] == 'complete') {
$start_level = 1;
$php_stmt = '$params';
while($start_level < $xml_elem['level']) {
$php_stmt .= '[$level['.$start_level.']]';
$start_level++;
}
$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
eval($php_stmt);
}
}
curl_close($ch);
//echo '<pre>'; print_r($params); echo'</pre>'; // Uncomment to see xml tags
return $params['RateV4Response']['1ST']['1']['RATE'];
}
echo USPSParcelRate();
this code doesn't give me any results unless i uncomment the print_r lines and it shows it like this:-
Array
(
[RATEV4RESPONSE] => Array
(
[1ST] => Array
(
[ZIPORIGINATION] => XXXXX
[ZIPDESTINATION] => XXXXX
[POUNDS] => 3
[OUNCES] => 5
[CONTAINER] => NONRECTANGULAR
[SIZE] => LARGE
[WIDTH] => 12
[LENGTH] => 16
[HEIGHT] => 6
[GIRTH] => 31
[ZONE] => 5
[1] => Array
(
[MAILSERVICE] => Priority Mail 3-Day<sup>™</sup>
[RATE] => 14.05
)
)
)
)
how can i echo the value of this line only :-
[RATE] => 14.05
Array keys are case sensitive, so...
return $params['RATEV4RESPONSE']['1ST'][1]['RATE'];
Should do it

Customize array from cURL XML response

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
)
)

Categories