从cURL XML响应自定义数组

时间:2012-08-03 22:19:13

标签: php xml curl

我需要从cURL请求输出具有指定格式的数组。我尝试了很多方法来根据需要格式化XML结果,但没有运气。

这是PHP代码

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

它打印以下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>

如果我应用$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
                        (
                        )
                )
        )
)

我需要返回的是和这样的数组。我尝试了几乎所有在其他问题中找到的方法,但从未有过构建这个二维数组的好方法。

array(
    'Option Name' => array(
       'id'=>'40045',
       'quote'=>'20,20',
       'days'=>'1',
    ),
    'Option Name' => array(
       'id'=>'40215',
       'quote'=>'29,27',
       'days'=>'3',
    )
) 

*之后将通过ID代码检索选项名称。

4 个答案:

答案 0 :(得分:5)

这应该完美无缺!

$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/

答案 1 :(得分:1)

尝试此功能(将响应传递给它,它应该返回你的数组):

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 :(得分:0)

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

为我着迷。

答案 3 :(得分:-1)

我终于明白了。在测试了你在谷歌上找到的所有建议和许多其他建议后,我想出了这个:

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

最后的秘诀是添加__toString()以将作为数组返回的值转换为简单字符串。它打印得很完美。谢谢你们!!

Array
(
    [PAC] => Array
        (
            [id] => 41106
            [quote] => 16,90
            [delivery_days] => 3
        )

    [SEDEX a Cobrar] => Array
        (
            [id] => 40045
            [quote] => 19,20
            [delivery_days] => 1
        )

)