How to echo a specific value in an array? - php

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

Related

Php Curl send File AND array data

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

how to Display values from nested array

Please help me to extract and display the values from this array..
This is the output when I do a print_r($array); :
Array
(
[0] => SPD Object
(
[DRIVERNAME] => SPD Barry
[STARTTIME] => 07:44
[FINISHTIME] => 18:12
[STOP] =>
[SEQUENCENO] => 37
[PLACENAME] => AMSTERDAM ZUIDOOST
[ARRIVALTIME] => 17:32
)
[1] => SPD Object
(
[DRIVERNAME] => SPD Brady
[STARTTIME] => 07:36
[FINISHTIME] => 15:53
[STOP] =>
[SEQUENCENO] => 32
[PLACENAME] => NIEUWEGEIN
[ARRIVALTIME] => 15:30
)
[2] => SPD Object
(
[DRIVERNAME] => SPD Bram
[STARTTIME] => 08:11
[FINISHTIME] => 18:32
[STOP] =>
[SEQUENCENO] => 32
[PLACENAME] => LAGE ZWALUWE
[ARRIVALTIME] => 17:28
)
)
What I want to do is, get this Driver Name and Sequence Number and echo them.
UPDATE :
My full code can be found below.
I get a xml file which contain this kind of stuff :
<TRIP>
<DRIVERNAME>SPD Barry</DRIVERNAME>
<STARTTIME>07:44</STARTTIME>
<FINISHTIME>18:12</FINISHTIME>
<STOP>
<SEQUENCENO>1</SEQUENCENO>
<PLACENAME>ROTTERDAM</PLACENAME>
<ARRIVALTIME>08:30</ARRIVALTIME>
</STOP>
</TRIP>
Here is my PHP file to collect data into an array.
<?php
class SPD {
function SPD ($aa) {
foreach ($aa as $k=>$v)
$this->$k = $aa[$k];
}
}
function readDatabase($filename) {
// read the XML database of aminoacids
$data = implode("", file($filename));
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, $data, $values, $tags);
xml_parser_free($parser);
// loop through the structures
foreach ($tags as $key=>$val) {
if ($key == "TRIP") {
$molranges = $val;
// each contiguous pair of array entries are the
// lower and upper range for each molecule definition
for ($i=0; $i < count($molranges); $i+=2) {
$offset = $molranges[$i] + 1;
$len = $molranges[$i + 1] - $offset;
$tdb[] = parseMol(array_slice($values, $offset, $len));
}
} else {
continue;
}
}
return $tdb;
}
function parseMol($mvalues) {
for ($i=0; $i < count($mvalues); $i++) {
$mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
}
return new SPD($mol);
}
$db = readDatabase("test.xml");
if(is_array($db)){
foreach($db as $item) {
echo $item->DRIVERNAME;
echo $item->SEQUENCENO;
}
}
?>
What I want to do is, echo Driver name and Sequence Number :)
This should do it :
<?php
class SPD {
function SPD($aa) {
foreach ($aa as $k => $v)
$this->$k = $aa[$k];
}
}
function readDatabase($filename) {
// read the XML database of aminoacids
$data = implode("", file($filename));
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, $data, $values, $tags);
xml_parser_free($parser);
// loop through the structures
foreach ($tags as $key => $val) {
if ($key == "TRIP") {
$molranges = $val;
// each contiguous pair of array entries are the
// lower and upper range for each molecule definition
for ($i = 0; $i < count($molranges); $i+=2) {
$offset = $molranges[$i] + 1;
$len = $molranges[$i + 1] - $offset;
$tdb[] = parseMol(array_slice($values, $offset, $len));
}
} else {
continue;
}
}
return $tdb;
}
function parseMol($mvalues) {
for ($i = 0; $i < count($mvalues); $i++) {
if(isset($mvalues[$i]["value"])) {
$mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
}
}
return new SPD($mol);
}
$db = readDatabase("test.xml");
if (is_array($db)) {
foreach ($db as $item) {
echo 'ITEM 1 : ' . "\n<br/>";
echo '---------------' . "\n<br/>";
echo 'DRIVERNAME : ' . $item->DRIVERNAME . "\n<br/>";
echo 'SEQUENCENO : ' . $item->SEQUENCENO . "\n\n<br/><br/>";
}
}
?>

How can I subtract 3 days from a date?

I have a sync script that syncs domain expiration dates with next due date for billing. Right now the script works great if you want the expiration date to equal the next due date.
But I need the next due date to be three days before the expiration, so I need the code to subtract 3 days from the $expirydate in the following code snippet (Full script code is below):
if ($SyncNextDueDate) {
update_query ( "tbldomains", array ("nextduedate" => $expirydate ), array ("domain" => $domainname ) );
}
Full code:
<?php
require dirname ( __FILE__ ) . '/../../../dbconnect.php';
require ROOTDIR . '/includes/functions.php';
require ROOTDIR . '/includes/registrarfunctions.php';
$cronreport = 'Internet.bs Domain Sync Report<br>
---------------------------------------------------<br>
';
/**
* gets expiration date from domain list command
* #param string $data - command TEXT response
* #return array - associative array having as key the domain name and as value the expiration date
*/
function parseResult($data) {
$result = array ();
$data=strtolower($data);
$arr = explode ( "\n", $data );
$totalDomains = 0;
$assocArr = array ();
foreach ( $arr as $str ) {
list ( $varName, $value ) = explode ( "=", $str );
$varName = trim ( $varName );
$value = trim ( $value );
if ($varName == "domaincount") {
$totalDomains = intval ( $value );
}
$assocArr [$varName] = $value;
}
if ($assocArr ["status"] != "success") {
return false;
}
for($i = 0; $i < $totalDomains; $i ++) {
list ( $y, $m, $d ) = explode ( "/", $assocArr ["domain_" . $i . "_expiration"] );
$status = strtolower ( $assocArr ["domain_" . $i . "_status"] );
if(!is_numeric($y) || !is_numeric($m) || !is_numeric($d)){
$ddat = array ("expiry" => null, "status" => $status );
} else {
$ddat = array ("expiry" => mktime ( 0, 0, 0, $m, $d, $y ), "status" => $status );
}
$result [strtolower ( $assocArr ["domain_" . $i . "_name"] )] = $ddat;
if (isset ( $assocArr ["domain_" . $i . "_punycode"] )) {
$result [strtolower ( $assocArr ["domain_" . $i . "_punycode"] )] = $ddat;
}
}
return $result;
}
$params = getregistrarconfigoptions ( 'internetbs' );
$postfields = array ();
$postfields ['ApiKey'] = $params ['Username'];
$postfields ['Password'] = $params ['Password'];
$postfields ['ResponseFormat'] = 'TEXT';
$postfields ['CompactList'] = 'no';
$testMode = trim(strtolower($params ['TestMode']))==="on";
$SyncNextDueDate = trim(strtolower($params ["SyncNextDueDate"]))==="on";
if ($testMode) {
$url = 'https://testapi.internet.bs/domain/list';
} else {
$url = 'https://api.internet.bs/domain/list';
}
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_USERAGENT, "WHMCS Internet.bs Corp. Expiry Sync Robot" );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postfields );
$data = curl_exec ( $ch );
$curl_err = false;
if (curl_error ( $ch )) {
$curl_err = 'CURL Error: ' . curl_errno ( $ch ) . ' - ' . curl_error ( $ch );
exit ( 'CURL Error: ' . curl_errno ( $ch ) . ' - ' . curl_error ( $ch ) );
}
curl_close ( $ch );
if ($curl_err) {
$cronreport .= "Error connecting to API: $curl_err";
} else {
$result = parseResult ( $data );
if (! $result) {
$cronreport .= "Error connecting to API:<br>" . nl2br ( $data ) . "<br>";
} else {
$queryresult = select_query ( "tbldomains", "domain", "registrar='internetbs' AND (status='Pending Transfer' OR status='Active')" );
while ( $data = mysql_fetch_array ( $queryresult ) ) {
$domainname = trim ( strtolower ( $data ['domain'] ) );
if (isset ( $result [$domainname] )) {
if(!is_null($result [$domainname] ["expiry"])){
$expirydate = date ( "Y-m-d", $result [$domainname] ["expiry"] );
} else {
$expirydate = false;
}
$status = $result [$domainname] ["status"];
if ($status == 'ok') {
update_query ( "tbldomains", array ("status" => "Active" ), array ("domain" => $domainname ) );
}
if ($expirydate) {
update_query ( "tbldomains", array ("expirydate" => $expirydate ), array ("domain" => $domainname ) );
if ($SyncNextDueDate) {
update_query ( "tbldomains", array ("nextduedate" => $expirydate ), array ("domain" => $domainname ) );
}
$cronreport .= '' . 'Updated ' . $domainname . ' expiry to ' . frommysqldate ( $expirydate ) . '<br>';
}
} else {
$cronreport .= '' . 'ERROR: ' . $domainname . ' - Domain does not appear in the account at Internet.bs.<br>';
}
}
}
}
logactivity ( 'Internet.bs Domain Sync Run' );
sendadminnotification ( 'system', 'WHMCS Internet.bs Domain Syncronisation Report', $cronreport );
?>
$date = new DateTime($expirydate);
$date->sub(new DateInterval('P3D');
$expirydate = $date->format('Y-m-d');
or as a one-liner:
$expirydate = (new DateTime($expirydate))->sub(new DateInterval('P3D'))->format('Y-m-d');
Here's a slightly different method:
$date = new DateTime($expirydate);
$date->modify('-3 days');
$expirydate = $date->format('Y-m-d');

WHMCS getclients searching results

Myself and a few friends are trying to use WHMCS to offer services in a virtual world. Issue is WHMCS does not provide a simple way to search for a specific client record without already having the client id, which wouldn't be stored anywhere besides the WHMCS database. the api function getclients returns results in an XML format, issue is when you search for a client using this method you can only search for firstname, lastname, or email address. Now we have tried passing the variables for firstname and lastname(they have to be passed separately) This unfortunatly returns the client records for all clients that X firstname OR Y Lastname, instead of narrowing down the one client with both X and Y.
What I want to know is how to search PHP array generated from an XML result to try and grab the client records for only the client we are looking for.
The results are posted as such:
Array ( [WHMCSAPI] => Array ( [ACTION] => getclients [RESULT] => success [TOTALRESULTS] => 2 [STARTNUMBER] => 0 [NUMRETURNED] => 2 [CLIENTS] => Array ( [CLIENT] => Array ( [ID] => 9 [FIRSTNAME] => Test1 [LASTNAME] => Test2 [COMPANYNAME] => [EMAIL] => test1#test.com [DATECREATED] => 2013-04-24 [GROUPID] => 1 [STATUS] => Active ) [CLIENT1] => Array ( [ID] => 20 [FIRSTNAME] => Test3 [LASTNAME] => Test2 [COMPANYNAME] => [EMAIL] => test#test.com [DATECREATED] => 2014-01-20 [GROUPID] => 0 [STATUS] => Active ) ) ) )
The code we try using to search is:
$postfields["action"] = "getclients";
$postfields["search"] = $firstname;
$postfields["search"] = $lastname;
$postfields["responsetype"] = "xml";
$query_string = "";
foreach ($postfields AS $k=>$v) $query_string .= "$k=".urlencode($v)."&";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$xml = curl_exec($ch);
if (curl_error($ch) || !$xml) $xml = '<whmcsapi><result>error</result>'.
'<message>Connection Error</message><curlerror>'.
curl_errno($ch).' - '.curl_error($ch).'</curlerror></whmcsapi>';
curl_close($ch);
$arr = whmcsapi_xml_parser($xml); # Parse XML
$client = searchClient($firstname, $lastname, $arr);
print_r($client); # Output XML Response as Array
/*
Debug Output - Uncomment if needed to troubleshoot problems
echo "<textarea rows=50 cols=100>Request: ".print_r($postfields,true);
echo "\nResponse: ".htmlentities($xml)."\n\nArray: ".print_r($arr,true);
echo "</textarea>";
*/
function whmcsapi_xml_parser($rawxml) {
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $rawxml, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
$alreadyused = array();
$x=0;
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (in_array($xml_elem['tag'],$alreadyused)) {
$x++;
$xml_elem['tag'] = $xml_elem['tag'].$x;
}
$level[$xml_elem['level']] = $xml_elem['tag'];
$alreadyused[] = $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);
}
}
return($params);
}
function searchClient($first, $last, $array)
{
foreach ($array as $key => $val)
{
if($val['FIRSTNAME'] == $first && $val['LASTNAME'] == $last)
{
return $key;
}
}
return null;
}
?>
This returns a blank result. I will admit I am not entirely sure how to do this so any pointers will help.
You are able to "search for a specific client record" via email address utilizing their api and they now support json format for responsetype
"Please note either the clientid or email is required."
http://docs.whmcs.com/API:Get_Clients_Details

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