Yasser1984
Yasser1984

Reputation: 2451

PHP Converting XML to array

I was trying to find a way to convert any xml feed into an associative array, I noticed many other people have looked for the same thing, and there has been many attempts, some of them have failed, I found the following way of doing it, credit goes to

http://gaarf.info/2009/08/13/xml-string-to-php-array/

I slightly changed the code, and here is the outcome.

    function xmlNameSpaceToArray(SimpleXmlIterator $xml, $nameSpaces=Null){
      $output = Null;
      $preparedArray = array();
      for($xml->rewind(); $xml->valid(); $xml->next()) {
        $key = $xml->key();
        if(!isset($preparedArray[$key])) { $preparedArray[$key] = array(); $i=0; }
        else $i = count($preparedArray[$key]);
        $simple = true;
        foreach($xml->current()->attributes() as $k=>$v) {
            $preparedArray[$key][$i][$k]=(string)$v;
            $simple = false;
        }
        if($nameSpaces) foreach($nameSpaces as $nid=>$name) {
          foreach($xml->current()->attributes($name) as $k=>$v) {
             $preparedArray[$key][$i][$nid.':'.$k]=(string)$v;
             $simple = false;
          }
        } 
        if($xml->hasChildren()) {
            if($simple) $preparedArray[$key][$i] = xmlNameSpaceToArray($xml->current(), $nameSpaces);
            else $preparedArray[$key][$i]['content'] = xmlNameSpaceToArray($xml->current(), $nameSpaces);
        } else {
            if($simple) $preparedArray[$key][$i] = strval($xml->current());
            else $preparedArray[$key][$i]['content'] = strval($xml->current());
        }
        $i++;
      }
      $output = $preparedArray;
      return $preparedArray;
    }

    function xmlToArray($xmlFilePath){
        $xml = new SimpleXmlIterator($xmlFilePath , null, true);
        $nameSpaces = $xml->getNamespaces(true);
        $output = xmlNameSpaceToArray($xml,$nameSpaces);
        return $output;
    }

    $xmlFilePath = 'http://forums.devshed.com/rss/feed-5.xml';
    $output = xmlToArray($xmlFilePath);
    print_r($output);

What I'm trying to find out now is potential problems this could have, the goal is to make this work for EVERY well structured XML feed, without any php warnings, notices and without losing any data.

Can you find a flaw in this or a feed that doesn't work? It worked for everything I tested it for.

Upvotes: 1

Views: 8107

Answers (3)

Vishnu Sharma
Vishnu Sharma

Reputation: 1383

http://php.net/manual/en/book.simplexml.php

The syntax looks something like this for your example

<aaaa Version="1.0">
   <bbb>
     <cccc>
       <dddd Id="id:pass" />
       <eeee name="hearaman" age="24" />
     </cccc>
   </bbb>
</aaaa>

PHP code

<?php
$xml = new SimpleXMLElement($xmlString);
echo $xml->bbb->cccc->dddd['Id'];
echo $xml->bbb->cccc->eeee['name'];
// or...........
foreach ($xml->bbb->cccc as $element) {
  foreach($element as $key => $val) {
   echo "{$key}: {$val}";
  }
}

Upvotes: 0

James Hall
James Hall

Reputation: 7693

Easiest way to do this is to use the built in functions, then convert to an array.

<?php
$obj = simplexml_load_string($xml); // Parse XML
$array = json_decode(json_encode($obj), true); // Convert to array
?>

Upvotes: 5

lasseoe
lasseoe

Reputation: 56

This piece of XML seems to break it.

<BackupJob ID="2011-11-09-05-00-00" StartTime="2011-11-09 04:56:51" EndTime="2011-11-09 05:02:01" BackupJobStatus="BS_STOP_SUCCESS" NumOfWarnEntries="0" NumOfErrorEntries="0" NumOfNewFiles="0" TotalNewFilesSize="0" NumOfUpdatedFiles="1" TotalUpdatedFilesSize="8709755" NumOfDeletedFiles="0" TotalDeletedFilesSize="0" NumOfMovedFiles="0" TotalMovedFilesSize="0" NumOfUpdatedPermissionFiles="0" TotalUpdatedPermissionFilesSize="0"></BackupJob>

Upvotes: 0

Related Questions