1

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.

4
  • What is $xml? And if you want to give credits, name the author as well, not just paste a link. Commented Nov 9, 2011 at 21:44
  • $xml is an object which is instance of PHP SimpleXml's SimpleXmlIterator class. I added data type definition to the function to make it more clear, notice that you don't need to use that function directly. I don't know the name of the author. Commented Nov 9, 2011 at 21:48
  • You can remove the lines $output = Null; and $output = $preparedArray; since together they don't really do anything, especially since you return $preparedArray Commented Nov 12, 2011 at 13:59
  • I can't think of a way to break it with well structured XML. I guess what is more interesting is what happens with badly formed XML Commented Nov 12, 2011 at 14:01

3 Answers 3

5

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
?>
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

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}";
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.