2012-07-20 29 views
-1

我有XML一样:需要XML转换成PHP数组

[domain] => Array 
(
    [0] => SimpleXMLElement Object 
     (
      [@attributes] => Array 
       (
        [name] => AlOkJainist 
        [com] => y 
        [comscore] => 805 
        [net] => y 
        [netscore] => 779 
        [tv] => y 
        [tvscore] => 753 
        [cc] => y 
        [ccscore] => 728 
       ) 

     ) 

    [1] => SimpleXMLElement Object 
     (
      [@attributes] => Array 
       (
        [name] => BargainsdiAlOg 
        [com] => y 
        [comscore] => 805 
        [net] => y 
        [netscore] => 779 
        [tv] => y 
        [tvscore] => 753 
        [cc] => y 
        [ccscore] => 728 
       ) 

     ) 

    [2] => SimpleXMLElement Object 
     (
      [@attributes] => Array 
       (
        [name] => AlOkayJain 
        [com] => y 
        [comscore] => 792 
        [net] => y 
        [netscore] => 766 
        [tv] => y 
        [tvscore] => 740 
        [cc] => y 
        [ccscore] => 715 
       ) 

     ) 

    ) 

) 

我想创建的PHP数组一样:

array(
    'AlOkJainist' => array([com] => y, [net] => y), 
    'BargainsdiAlOg' => array([com] => y, [net] => y), 
    'AlOkayJain' => array([com] => y, [net] => y), 

); 

请帮我,我都试过,但没有获得成功。

+4

[你有什么尝试?](http://www.whathaveyoutried.com/) – 2012-07-20 13:32:35

回答

0

您可以使用php提供的SimpleXML库。 传递xml文档,然后重新循环遍历并构建一个数组。

function toArray($obj, &$arr = null) { 
    if (is_null($arr)) $arr = array(); 
    if (is_string($obj)) $obj = new SimpleXMLElement($obj); 

    // Get attributes for current node and add to current array element 
    $attributes = $obj->attributes(); 
    foreach ($attributes as $attrib => $value) { 
     $arr['attributes'][$attrib] = (string)$value; 
    } 

    $children = $obj->children(); 
    $executed = false; 
    // Check all children of node 
    foreach ($children as $elementName => $node) { 
     // Check if there are multiple node with the same key and generate a multiarray 
     if($arr[$elementName] != null) { 
     if($arr[$elementName][0] !== null) { 
      $i = count($arr[$elementName]); 
      toArray($node, $arr[$elementName][$i]); 
     } else { 
      $tmp = $arr[$elementName]; 
      $arr[$elementName] = array(); 
      $arr[$elementName][0] = $tmp; 
      $i = count($arr[$elementName]); 
      toArray($node, $arr[$elementName][$i]); 
     } 
     } else { 
     $arr[$elementName] = array(); 
     toArray($node, $arr[$elementName]); 
     } 
     $executed = true; 
    } 
    // Check if is already processed and if already contains attributes 
    if(!$executed && $children->getName() == "" && !isset ($arr['attributes'])) { 
     $arr = (String)$obj; 
    } 
    return $arr; 
    }