1

我需要从 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

4 回答 4

7

这应该完美无缺!

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

于 2012-08-03T22:22:13.883 回答
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;
}
于 2012-08-03T22:33:01.603 回答
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.

于 2020-01-13T06:51:48.920 回答
-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
        )

)
于 2012-08-04T20:07:17.203 回答