动态访问simplexml对象

时间:2013-08-06 12:17:59

标签: php xml dynamic

考虑以下xml:

<?xml version="1.0" encoding="utf-8"?>
    <PP>
      <row merchant_id="xxxxxx" customer_code="xxxxxx" billing_name="xxxxxxx" account_status="Active" created_date="2013-08-01 08:26:31.710" last_modified_date="2013-08-01 08:26:52.170" last_trans_date="" billing_address1="" billing_address2="" billing_city="" billing_province_id="" billing_country_id="CA" billing_postal="" billing_email_address="mhussini@wilsons.ca" billing_phone="" velocity_group="" profile_group="" account_ref="987654" card_expiry="0813" cc_notification="" ref1="" ref2="" ref3="" ref4="" ref5="" />
      <row merchant_id="xxxxx" customer_code="xxxxxxx" billing_name="xxx" account_status="Active" created_date="2013-08-04 14:52:38.277" last_modified_date="2013-08-05 21:07:01.233" last_trans_date="2013-08-05 03:00:01.043" billing_address1="" billing_address2="" billing_city="" billing_province_id="" billing_country_id="CA" billing_postal="" billing_email_address="" billing_phone="" velocity_group="" profile_group="" account_ref="" card_expiry="0813" cc_notification="" ref1="" ref2="" ref3="" ref4="" ref5="" />
    </PP>

这给了我一个像这样简单的对象:

SimpleXMLElement Object ( [@attributes] => Array ( [merchant_id] => xxxxx [customer_code] => 987654 [billing_name] => John Doe [account_status] => Active [created_date] => 2013-08-01 08:26:31.710 [last_modified_date] => 2013-08-01 08:26:52.170 [last_trans_date] => [billing_address1] => [billing_address2] => [billing_city] => [billing_province_id] => [billing_country_id] => CA [billing_postal] => [billing_email_address] => mhussini@wilsons.ca [billing_phone] => [velocity_group] => [profile_group] => [account_ref] => 987654 [card_expiry] => 0813 [cc_notification] => [ref1] => [ref2] => [ref3] => [ref4] => [ref5] => ) )

我知道我可以像这样访问不同的行:

$xml = simplexml_load_string($resp)->row[0];

我现在想要做的是将$ xml变量作为索引数组访问,或者能够遍历对象而不知道将什么值传递给xml。

我还希望能够获得在simplexmlobject中传回的数组中的所有键。

我希望能够做到这样的事情:

for($i = 0;$i < count($xml);$i++){
    $keys = array_keys($xml[$i]);

    for($j = 0;$j < count($keys);$j++){
        echo $keys[$j].' ';
        echo $xml[$i][$j];
    }
}

1 个答案:

答案 0 :(得分:0)

类似的东西,我认为($ PP是你的SimpleXMLElement):

foreach ($PP->PP->row as $data) {
    foreach ($data as $attribute) {
    print_r($data);
}