xml新手:将子数据转换为php变量

时间:2013-02-15 14:12:42

标签: php xml-parsing

我的确认表需要一个平均而精益的解决方案。我从服务器XML响应中检索联系人电子邮件地址。具体如下:

<users>
<User LoginName="test1" Owner="" Alias="" UserType="PAID" ClientType="OBM" 
Quota="10737418240" Timezone="GMT+08:00 (CST)" Language="en" DataFile="1" 
DataSize="1536" RetainFile="0" RetainSize="0" EnableMSSQL="Y" EnableMSExchange="Y"
EnableOracle="Y" EnableLotusNotes="Y" EnableLotusDomino="Y" EnableMySQL="Y" 
EnableInFileDelta="Y" EnableShadowCopy="Y" EnableExchangeMailbox="N" 
ExchangeMailboxQuota="0" EnableNASClient="Y" EnableDeltaMerge="Y" EnableMsVm="N" 
MsVmQuota="0" EnableVMware="N" VMwareQuota="0" Bandwidth="0" Notes="" 
Status="ENABLE" RegistrationDate="1302687743242" SuspendPaidUser="N" 
SuspendPaidUserDate="20140503" LastBackupDate="1302699594652" EnableCDP="Y" 
EnableShadowProtectBareMetal="Y" EnableWinServer2008BareMetal="Y" 
Hostname="123.abc.com">
<Contact Name=""Email="www@qqq.com"/>
</user> 
…
</users>

我得到了以下结果:

object(SimpleXMLElement)#7 (1) { [0]=> string(6) "Company" } 
object(SimpleXMLElement)#8 (1) { [0]=> string(26) "email@address.ext" }

现在我需要将它们变成变量。我好像无法完成这件事。我的代码到了这里:

    $request = "http://$SERVER/obs/api/GetUser.do?
    SysUser=$SYSUSER&SysPwd=$SYSPWD&LoginName=$logonname";
    // Execute the API Call and place the XML output in an Array variable
    $response = simplexml_load_file($request);
    // Retrieve the LoginName attribute from the Array
    foreach($response->children() as $child) {   
        foreach($child->attributes() as $data) {
            echo var_dump($data);
        }
     }

任何新手的帮助都会受到影响。谢谢

1 个答案:

答案 0 :(得分:0)

以下是从XML中读取名称和电子邮件的简单示例:

$response = simplexml_load_file($request);

foreach($response->User as $user)
{
    foreach($user->Contact as $contact)
    {
        $name = $contact->attributes()->Name;
        $email = $contact->attributes()->Email;

        echo $name;
        echo $email;
    }
}

Demo