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.

4 Answers 4

7

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/

Sign up to request clarification or add additional context in comments.

4 Comments

Sorry my dumbness, but it end up printing almost the same array as I posted. That is, I still don't know how to get to the desired results from there! :/
For me it seems like I need to perform a foreach loop on the 2nd dimension of the array (the one with [0], [1] as keys) to make them keys of the new final array, and yet access the data from the 3rd dimension to make them the array as value. I just don't know how to do that. :(
wait I will help you through.
run the modified code and let me know how much close we are! Note, i have not tested it.
1

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

2 Comments

Did it. Replaced the return $array; with a print_r($array) and it almost nailed it. But instead of [id]=>41106 as key=>value it printed key=>array([0]=>value)
I folowed what you posted, it souldn't happen ... anyway if that happend, just replace 'id' => $node->Codigo,in my code with 'id' => $node->Codigo[0], and it should be fine
1
 $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.

Comments

-1

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
        )

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.