2010-08-07 70 views
0

所以我有這樣的XML結構:XML解析成數組

<fields> 
    <field name="agent_description" label="Agent Description" size="area" /> 
    <field name="agent_phone" label="Agent Phone" size="field" /> 
    <field name="agent_email" label="Agent EMail" size="field" /> 
    <field name="agent_listing_url" label="Agent Listing" size="field" /> 
    <field name="profile_video_title" label="Profile Video Title" size="field" /> 
    <field name="profile_video_sub_title" label="Profile Video Sub Title" size="field" /> 
    <field name="profile_video_url" label="Profile Video (YouTube)" size="field" /> 

</fields> 

我想解析到一個數組結構,看起來像這樣的:

array(
      array("name" => "agent_description", 
       "label" => "Agent Description", 
       "size" => "area"), 

      array("name" => "agent_phone", 
       "label" => "Agent Phone", 
       "size" => "field"), 

      array("name" => "agent_email", 
       "label" => "Agent EMail", 
       "size" => "field"), 

      array("name" => "agent_listing_url", 
       "label" => "Agent Listing", 
       "size" => "field"), 

      array("name" => "profile_video_title", 
       "label" => "Profile Video Title", 
       "size" => "field"), 

      array("name" => "profile_video_sub_title", 
       "label" => "Profile Video Sub Title", 
       "size" => "field"), 

      array("name" => "profile_video_url", 
       "label" => "Profile Video (YouTube)", 
       "size" => "field"), 
) 

最新最好的方式做到這一點?

回答

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

並非所有服務器啓用的SimpleXML。 – Alexander 2010-08-07 02:36:40

+0

很好,謝謝。 – 2010-08-07 03:00:00

2
$dom = new DOMDocument; 
$dom->loadXML($xml); 
$fields = $dom->getElementsByTagName('field'); 
$arr = array(); 
foreach ($fields as $field) { 
    $arr[] = array(
    'name' => $field->getAttribute('name'), 
    'label' => $field->getAttribute('label'); 
    'size' => $field->getAttribute('size'), 
); 
}