1

Estoy tratando de realizar extracción de datos con PHP, pero me marca de esta forma mi prin_r:

$532.87 
PesosSimpleXMLElement Object ( 
[@attributes] => Array ( 
    [xmlnsSOAPENV] => http//schemas.xmlsoap.org/soap/envelope/ ) 
    [SOAPENVHeader] => SimpleXMLElement Object ( ) 
    [SOAPENVBody] => SimpleXMLElement Object ( 
        [RateReply] => SimpleXMLElement Object ( 
            [HighestSeverity] => NOTE 
            [Notifications] => Array ( [0] => SimpleXMLElement Object ( [Severity] => NOTE [Source] => crs [Code] => 819 [Message] => The origin state/province code has been changed. [LocalizedMessage] => The origin state/province code has been changed. ) [1] => SimpleXMLElement Object ( [Severity] => NOTE [Source] => crs [Code] => 820 [Message] => The destination state/province code has been changed. [LocalizedMessage] => The destination state/province code has been changed. ) ) 
            [TransactionDetail] => SimpleXMLElement Object ( [CustomerTransactionId] => SimpleXMLElement Object ( ) ) 
            [Version] => SimpleXMLElement Object ( [ServiceId] => crs [Major] => 14 [Intermediate] => 0 [Minor] => 0 ) 
            [RateReplyDetails] => SimpleXMLElement Object ( 
                [ServiceType] => FIRST_OVERNIGHT 
                [PackagingType] => YOUR_PACKAGING 
                [DeliveryStation] => QROA 
                [DeliveryDayOfWeek] => FRI 
                [DeliveryTimestamp] => 20210528T083000 
                [CommitDetails] => SimpleXMLElement Object ( 
                    [ServiceType] => FIRST_OVERNIGHT 
                    [CommitTimestamp] => 20210528T083000 
                    [DayOfWeek] => FRI 
                    [DestinationServiceArea] => A1 
                    [BrokerToDestinationDays] => 0 
                    [DocumentContent] => NON_DOCUMENTS 
                ) 
                [DestinationAirportId] => QRO 
                [IneligibleForMoneyBackGuarantee] => false 
                [OriginServiceArea] => AA 
                [DestinationServiceArea] => A1 
                [SignatureOption] => SERVICE_DEFAULT 
                [ActualRateType] => PAYOR_ACCOUNT_SHIPMENT 
                [RatedShipmentDetails] => Array ( 
                    [0] => SimpleXMLElement Object ( 
                        [EffectiveNetDiscount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) 
                        [ShipmentRateDetail] => SimpleXMLElement Object ( 
                            [RateType] => PAYOR_ACCOUNT_SHIPMENT 
                            [RateScale] => 0000000 
                            [RateZone] => R0003 
                            [PricingCode] => BASE 
                            [RatedWeightMethod] => ACTUAL 
                            [CurrencyExchangeRate] => SimpleXMLElement Object ( [FromCurrency] => NMP [IntoCurrency] => NMP [Rate] => 1.0 ) 
                            [DimDivisor] => 0 
                            [FuelSurchargePercent] => 9.0 
                            [TotalBillingWeight] => SimpleXMLElement Object ( [Units] => KG [Value] => 1.0 ) 
                            [TotalBaseCharge] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 421.44 ) 
                            [TotalFreightDiscounts] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) 
                            [TotalNetFreight] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 421.44 ) 
                            [TotalSurcharges] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 37.93 ) 
                            [TotalNetFedExCharge] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 459.37 ) 
                            [TotalTaxes] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 73.5 ) 
                            [TotalNetCharge] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 532.87 ) 
                            [TotalRebates] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) 
                            [TotalDutiesAndTaxes] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) 
                            [TotalNetChargeWithDutiesAndTaxes] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 532.87 ) 
                            [Surcharges] => Array ( [0] => SimpleXMLElement Object ( [SurchargeType] => RESIDENTIAL_DELIVERY [Description] => Residential delivery [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) ) [1] => SimpleXMLElement Object ( [SurchargeType] => FUEL [Description] => Fuel [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 37.93 ) ) ) [Taxes] => SimpleXMLElement Object ( [TaxType] => VAT [Description] => Mexico freight valueadded [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 73.5 ) ) ) ) 
                    [1] => SimpleXMLElement Object ( [EffectiveNetDiscount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) [ShipmentRateDetail] => SimpleXMLElement Object ( [RateType] => RATED_ACCOUNT_SHIPMENT [RateScale] => 0000000 [RateZone] => R0003 [PricingCode] => BASE [RatedWeightMethod] => ACTUAL [CurrencyExchangeRate] => SimpleXMLElement Object ( [FromCurrency] => NMP [IntoCurrency] => NMP [Rate] => 1.0 ) [DimDivisor] => 0 [FuelSurchargePercent] => 9.0 [TotalBillingWeight] => SimpleXMLElement Object ( [Units] => KG [Value] => 1.0 ) [TotalBaseCharge] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 421.44 ) [TotalFreightDiscounts] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) [TotalNetFreight] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 421.44 ) [TotalSurcharges] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 37.93 ) [TotalNetFedExCharge] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 459.37 ) [TotalTaxes] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 73.5 ) [TotalNetCharge] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 532.87 ) [TotalRebates] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) [TotalDutiesAndTaxes] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) [TotalNetChargeWithDutiesAndTaxes] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 532.87 ) [Surcharges] => Array ( [0] => SimpleXMLElement Object ( [SurchargeType] => RESIDENTIAL_DELIVERY [Description] => Residential delivery [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) ) [1] => SimpleXMLElement Object ( [SurchargeType] => FUEL [Description] => Fuel [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 37.93 ) ) ) [Taxes] => SimpleXMLElement Object ( [TaxType] => VAT [Description] => Mexico freight valueadded [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 73.5 ) ) ) ) 
                    [2] => SimpleXMLElement Object ( [ShipmentRateDetail] => SimpleXMLElement Object ( [RateType] => PAYOR_LIST_SHIPMENT [RateScale] => 0000000 [RateZone] => R0003 [PricingCode] => BASE [RatedWeightMethod] => ACTUAL [CurrencyExchangeRate] => SimpleXMLElement Object ( [FromCurrency] => NMP [IntoCurrency] => NMP [Rate] => 1.0 ) [DimDivisor] => 0 [FuelSurchargePercent] => 9.0 [TotalBillingWeight] => SimpleXMLElement Object ( [Units] => KG [Value] => 1.0 ) [TotalBaseCharge] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 421.44 ) [TotalFreightDiscounts] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) [TotalNetFreight] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 421.44 ) [TotalSurcharges] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 37.93 ) [TotalNetFedExCharge] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 459.37 ) [TotalTaxes] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 73.5 ) [TotalNetCharge] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 532.87 ) [TotalRebates] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) [TotalDutiesAndTaxes] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) [TotalNetChargeWithDutiesAndTaxes] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 532.87 ) [Surcharges] => Array ( [0] => SimpleXMLElement Object ( [SurchargeType] => RESIDENTIAL_DELIVERY [Description] => Residential delivery [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) ) [1] => SimpleXMLElement Object ( [SurchargeType] => FUEL [Description] => Fuel [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 37.93 ) ) ) [Taxes] => SimpleXMLElement Object ( [TaxType] => VAT [Description] => Mexico freight valueadded [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 73.5 ) ) ) ) 
                    [3] => SimpleXMLElement Object ( [ShipmentRateDetail] => SimpleXMLElement Object ( [RateType] => RATED_LIST_SHIPMENT [RateScale] => 0000000 [RateZone] => R0003 [PricingCode] => BASE [RatedWeightMethod] => ACTUAL [CurrencyExchangeRate] => SimpleXMLElement Object ( [FromCurrency] => NMP [IntoCurrency] => NMP [Rate] => 1.0 ) [DimDivisor] => 0 [FuelSurchargePercent] => 9.0 [TotalBillingWeight] => SimpleXMLElement Object ( [Units] => KG [Value] => 1.0 ) [TotalBaseCharge] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 421.44 ) [TotalFreightDiscounts] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) [TotalNetFreight] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 421.44 ) [TotalSurcharges] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 37.93 ) [TotalNetFedExCharge] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 459.37 ) [TotalTaxes] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 73.5 ) [TotalNetCharge] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 532.87 ) [TotalRebates] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) [TotalDutiesAndTaxes] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) [TotalNetChargeWithDutiesAndTaxes] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 532.87 ) [Surcharges] => Array ( [0] => SimpleXMLElement Object ( [SurchargeType] => RESIDENTIAL_DELIVERY [Description] => Residential delivery [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) ) [1] => SimpleXMLElement Object ( [SurchargeType] => FUEL [Description] => Fuel [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 37.93 ) ) ) [Taxes] => SimpleXMLElement Object ( [TaxType] => VAT [Description] => Mexico freight valueadded [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 73.5 ) ) ) ) 
                ) 
            ) 
        ) 
    ) 
)

El código es el siguiente:

   foreach($result as $dattos)
{
echo "mis archivos: " . $dattos->SurchargeType; echo "<br>";
echo "extra: " . $dattos->TotalNetCharge; echo "<br>";
echo "Description: " . $dattos->SurchargeType; echo "<br>"; echo "<br>";
}

Y lo que trato de extraer son varios campos, por ejemplo los códigos postales, ciudad de origen y de destino:

Aquí esta mi XML, que lo hice en PHP:

$xml = '<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://fedex.com/ws/rate/v14"><SOAP-ENV:Body><ns1:RateRequest>
<ns1:WebAuthenticationDetail>
<ns1:UserCredential>
<ns1:Key>'.$key.'</ns1:Key>
<ns1:Password>'.$password.'</ns1:Password>
</ns1:UserCredential></ns1:WebAuthenticationDetail>
<ns1:ClientDetail>
<ns1:AccountNumber>'.$account_number.'</ns1:AccountNumber>
<ns1:MeterNumber>'.$meter_number.'</ns1:MeterNumber>
</ns1:ClientDetail>
<ns1:TransactionDetail><ns1:CustomerTransactionId> *** Rate Request v14 using PHP ***</ns1:CustomerTransactionId></ns1:TransactionDetail><ns1:Version><ns1:ServiceId>crs</ns1:ServiceId><ns1:Major>14</ns1:Major><ns1:Intermediate>0</ns1:Intermediate><ns1:Minor>0</ns1:Minor></ns1:Version><ns1:ReturnTransitAndCommit>true</ns1:ReturnTransitAndCommit><ns1:RequestedShipment>
<ns1:DropoffType>REGULAR_PICKUP</ns1:DropoffType>
<ns1:ServiceType>'.$ServiceType.'</ns1:ServiceType>
<ns1:PackagingType>'.$PackagingType.'</ns1:PackagingType>
<ns1:Shipper><ns1:Contact><ns1:PersonName>Sender Name</ns1:PersonName><ns1:CompanyName>Sender Company Name</ns1:CompanyName><ns1:PhoneNumber></ns1:PhoneNumber></ns1:Contact><ns1:Address><ns1:StreetLines></ns1:StreetLines><ns1:City></ns1:City><ns1:StateOrProvinceCode></ns1:StateOrProvinceCode>
<ns1:PostalCode>'.$origenPostalCode.'</ns1:PostalCode><ns1:CountryCode>'.$origenPais.'</ns1:CountryCode></ns1:Address></ns1:Shipper>
<ns1:Recipient><ns1:Contact><ns1:PersonName>Recipient Name</ns1:PersonName><ns1:CompanyName>Company Name</ns1:CompanyName><ns1:PhoneNumber></ns1:PhoneNumber></ns1:Contact><ns1:Address><ns1:StreetLines></ns1:StreetLines><ns1:City></ns1:City><ns1:StateOrProvinceCode></ns1:StateOrProvinceCode>
<ns1:PostalCode>'.$destinoPostalCode.'</ns1:PostalCode>
<ns1:CountryCode>'.$destinoPais.'</ns1:CountryCode><ns1:Residential>false</ns1:Residential></ns1:Address></ns1:Recipient><ns1:ShippingChargesPayment><ns1:PaymentType>SENDER</ns1:PaymentType><ns1:Payor>
<ns1:ResponsibleParty>
<ns1:AccountNumber>'.$account_number.'</ns1:AccountNumber>
</ns1:ResponsibleParty>
</ns1:Payor></ns1:ShippingChargesPayment>



<ns1:RateRequestTypes>ACCOUNT</ns1:RateRequestTypes><ns1:PackageCount>1</ns1:PackageCount><ns1:RequestedPackageLineItems><ns1:SequenceNumber>1</ns1:SequenceNumber>
<ns1:GroupPackageCount>'.$GroupPackageCount.'</ns1:GroupPackageCount>
<ns1:Weight><ns1:Units>'.$WeightTipo.'</ns1:Units><ns1:Value>'.$WeightValue.'</ns1:Value></ns1:Weight>
<ns1:Dimensions>
<ns1:Length>'.$Length.'</ns1:Length>
<ns1:Width>'.$Width.'</ns1:Width>
<ns1:Height>'.$Height.'</ns1:Height>
<ns1:Units>'.$Units.'</ns1:Units>
</ns1:Dimensions>
</ns1:RequestedPackageLineItems>
</ns1:RequestedShipment></ns1:RateRequest></SOAP-ENV:Body></SOAP-ENV:Envelope>';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$result_xml = curl_exec($ch);


$result_xml = str_replace(array(':','-'), '', $result_xml);
$result = @simplexml_load_string($result_xml);
curl_close($ch);

Y aquí como lo estoy mostrando:

introducir la descripción de la imagen aquí El precio si me los muestra, no hay problema con ese, pero el problema son los demás campos; este es el precio:

echo 'Precio <br></div>'.'$'.$result->SOAPENVBody->RateReply->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount.' Pesos';

Quiero que me lo muestre en orden como lo voy agregando

10
  • De nuevo, como en la otra pregunta, hazle print_r a la variable donde tienes la respuesta (o haz var_dump) para que revises qué te está llegando y por qué la variable es nula
    – Alfabravo
    Commented el 27 may. 2021 a las 17:24
  • vale vale, ya lo agrege a mi respueta Commented el 27 may. 2021 a las 17:27
  • en si creo que si me trae los datos pero no me muestra nada con el echo foreach Commented el 27 may. 2021 a las 17:32
  • Y bueno, identificas los rate reply ahí? o tal vez con echo u otra opción se vea más claro. La cosa es que php te está diciendo que $xml->SOAPENVBody->RateReply no es nada y la misión es identificar el porqué
    – Alfabravo
    Commented el 27 may. 2021 a las 17:33
  • En el código donde muestras cómo imprimes el precio, la variable es $result. En el código que falla, es $xml. Haces algo en medio? Estás jalando el precio de un dato diferente?
    – Alfabravo
    Commented el 27 may. 2021 a las 17:41

1 respuesta 1

2

Tú tenías en tu pregunta original algo propuesto similar a:

$respuesta = curl_exec($ch);
$xml = simplexml_load_string($respuesta);
foreach( $xml->SOAPENVBody->RateReply as $item ){
   echo 'Nombre: '.$item->Severity.'<br>';
   echo 'Nombre: '.$item->PackagingType.'<br>';
   echo 'Nombre: '.$item->destinoPostalCode.'<br>';
}

var_dump($xml->SOAPENVBody->RateReply)

Ya lo quitaste y ya estás viendo cómo llegan los datos, donde vemos que no tiene sentido hacer un foreach en RateReply porque sólo hay uno. Ahora, intentas hacer un foreach pintando datos como surchargeType y demás, pero no estás usando para nada el ejemplo del precio que tú mismo das, ni te esfuerzas por entender cómo está la estructura que estás recibiendo (ni le diste formato) y cómo replicar el ejemplo del precio, tirando unos foreach sin mucho análisis.

El ejemplo que tú mismo das:

echo 'Precio <br></div>'.'$'.$result->SOAPENVBody->RateReply->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount.' Pesos';

Ese echo llega al primer RatedShipmentDetails de los 4 que llegan, busca el elemento TotalNetCharge y busca el atributo Amount

...
[TotalNetCharge] => SimpleXMLElement Object ( 
    [Currency] => NMP 
    [Amount] => 532.87 
) 
...

Si le echas ganas y le das formato al objeto de salida, siempre será más fácil entender cómo acceder a las cosas. Cambiando ese foreach que pintas sin ningún contexto (porque recibes un único body con un único rateReply) y diciendo algo como esto:

$result_surcharges = $result->SOAPENVBody->RateReply->RateReplyDetails->RatedShipmentDetails->ShipmentRateDetail->Surcharges;

foreach($result_surcharges as $dattos) {
  echo "mis archivos: " . $dattos->SurchargeType; echo "<br>";
  echo "extra: " . $dattos->Amount->Amount; echo "<br>";
}

Esto te va a recorrer sólo los surcharges (que es un array)

[Surcharges] => Array ( 
    [0] => SimpleXMLElement Object ( 
        [SurchargeType] => RESIDENTIAL_DELIVERY 
        [Description] => Residential delivery 
        [Amount] => SimpleXMLElement Object ( 
            [Currency] => NMP 
            [Amount] => 0.0 
        ) 
    ) 
    [1] => SimpleXMLElement Object ( 
        [SurchargeType] => FUEL 
        [Description] => Fuel 
        [Amount] => SimpleXMLElement Object ( 
            [Currency] => NMP 
            [Amount] => 37.93 
        ) 
    ) 
) 
[Taxes] => SimpleXMLElement Object ( [TaxType] => VAT [Description] => Mexico freight valueadded [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 73.5 ) ) ) ) 

y así con todo. Revisa la estructura que recibes y recórrela acorde a lo que ves

4
  • perfecto gracis asi es como lo queria imlementar y si como dices eh estado buscando las propiedades para ete mas datos necesarioss gracias Commented el 28 may. 2021 a las 19:05
  • @slokersillo dale, ánimo que ya casi lo tienes. Revisa y, si la respuesta te resolvió tu duda, recuerda marcarla como aceptada para que otros sepan cómo enfrentarse con este tipo de problemas
    – Alfabravo
    Commented el 28 may. 2021 a las 19:07
  • si claro disculpa de donde tomaste este array [Surcharges] => Array ( [0] => SimpleXMLElement Object ( [SurchargeType] => RESIDENTIAL_DELIVERY [Description] => Residential delivery [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 0.0 ) ) [1] => SimpleXMLElement Object ( [SurchargeType] => FUEL [Description] => Fuel [Amount] => SimpleXMLElement Object ( [Currency] => NMP [Amount] => 37.93 ) ) para buscarlo pormicue Commented el 28 may. 2021 a las 19:11
  • Está DENTRO del objeto que recibes. En qué ruta? revisa el código del foreach sugerido, $result_surcharges recibe el objeto en esa ruta. Revisa tu pregunta, la edité dándole formato a la data que recibes
    – Alfabravo
    Commented el 28 may. 2021 a las 19:11

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.