从simpleXMLElementObject访问数据

时间:2013-08-01 17:08:36

标签: php xml

我从api获取XML数据,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<PP>
<row merchant_id="" customer_code="" billing_name="" account_status="Active"  created_date="2013-07-31 13:22:32.687" last_modified_date="2013-07-31 13:23:41.827" last_trans_date="2013-07-31 13:35:59.257" billing_address1="rd." billing_address2="" billing_city="Lower" billing_province_id="" billing_country_id="CA" billing_postal="" billing_email_address="" billing_phone="" velocity_group="" profile_group="" account_ref="12345" card_expiry="0713" cc_notification="" ref1="" ref2="" ref3="" ref4="" ref5="" />
</PP>

我试图访问php中的数据或将其转换为易于访问的数组。我尝试过这样的事情:

$xml = simplexml_load_string($resp);


$fields = array();
foreach ($xml->field as $f) {
    $f = (array) $f->attributes();
    $fields[] = $f['@attributes'];
}

但无法从中访问数据。

当我打印出数据时,它显示为:

SimpleXMLElement对象([row] =&gt;数组([0] =&gt; SimpleXMLElement对象([@attributes] =&gt;数组([merchant_id] =&gt; [customer_code] =&gt; [billing_name] =&gt; John Doe [account_status] =&gt;有效[created_date] =&gt; 2013-08-01 08:26:31.710 [last_modified_date] =&gt; 2013-08-01 08:26:52.170 [last_trans_date] =&gt; [billing_address1] =&gt; [billing_address2] =&gt; [billing_city] =&gt; [billing_proounince_id] =&gt; [billing_country_id] =&gt; CA [billing_postal] =&gt; [billing_email_address] =&gt; .ca [billing_phone] =&gt; [velocity_group ] =&gt; [profile_group] =&gt; [account_ref] =&gt; [card_expiry] =&gt; 0813 [cc_notification] =&gt; [ref1] =&gt; [ref2] =&gt; [ref3] =&gt; [ref4] =&gt; [ref5] =&gt;))[1] =&gt; SimpleXMLElement对象([@ attribute] =&gt;数组([merchant_id] =&gt; [customer_code] =&gt; 12345 [billing_name] =&gt; [account_status ] =&gt;有效[created_date] =&gt; 2013-07-31 13:22:32.687 [last_modified_date] =&gt; 2013-07-31 13:23:41.827 [last_trans_da te] =&gt; 2013-07-31 13:35:59.257 [billing_address1] =&gt; RD。 [billing_address2] =&gt; [billing_city] =&gt; Lowe [billing_province_id] =&gt; [billing_country_id] =&gt; CA [billing_postal] =&gt; [billing_email_address] =&gt; [billing_phone] =&gt; [velocity_group] =&gt; [profile_group] =&gt; [account_ref] =&gt; 12345 [card_expiry] =&gt; 0713 [cc_notification] =&gt; [ref1] =&gt; [ref2] =&gt; [ref3] =&gt; [ref4] =&gt; [ref5] =&gt; ))))

任何人都可以帮助我访问数据或帮助我将其放入数组中。

由于

1 个答案:

答案 0 :(得分:0)

像这样访问它:

$xml = simplexml_load_string($x)->row; // assume XML in $x
echo $xml['billing_country_id'];

将输出

CA

这很简单,不是吗。

看到它有效:https://eval.in/40171