views:

49

answers:

2

I need a function that takes a string as XML input and change that into an array. Example:

<a>
 <b>
  <c></c>
 </b>
</a>

So I can read it in PHP like this:

$array = xml2array($xmlcode);
echo $array['a']['b']['c'];

Note: I tried all xml2array functions in PHP's documentation on xml_parse, and they all didn't work or had problems.

+2  A: 

You can do something very similar ($xml->a->b->c) with SimpleXML.

See the basic usage examples.

EDIT (see comments):

You can do, for the first entry:

echo $xml->entry[0]->details;

or, for every entry:

foreach ($xml as $entry) {
    echo $entry->details;
}
Artefacto
I can not do this, since I need to actually use <entries><entry><name>bla</name></entry><entry><name>bla2</name></entry>...</entries>
Angelo
@Angelo SimpleXML can handle that in a simple fashion. See the page I've linked.
Artefacto
For some reason <details> isn't coming through. <entries> <entry> <name>Bla</name> <details> verylongcode-verylongcode-verylongcode </details> </entry> </entries>
Angelo
Damnit, no markup there.
Angelo
You _could_ edit your question to include that information.
VolkerK
A: 

Do you need an array, or would objects be sufficient?

$root = new SimpleXMLElement($xmlcode);

echo $root->b->c;

SimpleXML Documentation: http://www.php.net/simplexml

Jordan Ryan Moore