[英]SimpleXML, trying to loop through elements and create associative array out of values
我也無法使SimpleXML正常工作。 我想用元素創建一個關聯數組。 這是xml的樣子
<?xml version="1.0"?>
<RateV4Response>
<Package ID="1">
<ZipOrigination>11901</ZipOrigination>
<ZipDestination>91730</ZipDestination>
<Pounds>0</Pounds>
<Ounces>3.5</Ounces>
<Size>REGULAR</Size>
<Machinable>TRUE</Machinable>
<Zone>8</Zone>
<Postage CLASSID="3">
<MailService>Express Mail</MailService>
<Rate>28.00</Rate>
</Postage>
<Postage CLASSID="2">
<MailService>Express Mail Hold For Pickup</MailService>
<Rate>28.00</Rate>
</Postage>
MailService和Rate應該是一個數組。 這是我的PHP:
$usps_response = new SimpleXMLElement($result);
foreach($usps_response->Package->Postage as $service)
$data[] = array($service->MailService => $service->Rate);
我在這里沒有看到錯誤,但是$ data是28個空元素。 我也試過這個:
$data[] = array($service['MailService'] => $service['Rate']);
但這沒有幫助
如果僅將$ service分配給$ data [],則可以看到28個元素,每個元素具有3個子元素(屬性,MailService和Rate)。
我究竟做錯了什么?
這是圖片以幫助查看數據
這里發布的XML是無效的XML,因此我必須假定它不是完整的,或者郵政服務所生成的內容不是很有用。 進行了一些更改,就可以使它起作用。 請參閱http://www.laprbass.com/RAY_temp_user193.php
<?php // RAY_temp_user193.php
error_reporting(E_ALL);
echo '<pre>';
// TEST DATA
$xml = <<<ENDXML
<?xml version="1.0"?>
<RateV4Response>
<Package ID="1">
<ZipOrigination>11901</ZipOrigination>
<ZipDestination>91730</ZipDestination>
<Pounds>0</Pounds>
<Ounces>3.5</Ounces>
<Size>REGULAR</Size>
<Machinable>TRUE</Machinable>
<Zone>8</Zone>
<Postage CLASSID="3">
<MailService>Express Mail</MailService>
<Rate>28.00</Rate>
</Postage>
<Postage CLASSID="2">
<MailService>Express Mail Hold For Pickup</MailService>
<Rate>28.00</Rate>
</Postage>
</Package>
</RateV4Response>
ENDXML;
// MAKE AN OBJECT
$obj = SimpleXML_Load_String($xml);
var_dump($obj);
現在您想對這個對象做什么?
您似乎想在陣列中使用Express Mail Hold For Pickup
類的鍵,但是現在我們開始:
foreach($usps_response->Package->Postage as $service)
$data[] = array((string)$service->MailService => (string)$service->Rate);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.