1

So I have XML in the following format which I am reading from file 'test.xml'

<XML>
<Agent ID="ABC123">
    <Property>
        <Code>XYZ</Code>
        <Name>Hotel 1</Name>
    </Property>
    <Property>
        <Code>237</Code>
        <Name>Hotel 2</Name>
    </Property>
    <Property>
        <Code>213</Code>
        <Name>Hotel 3</Name>
    </Property>
</Agent>
<Agent ID="DEF456">
    <Property>
        <Code>333</Code>
        <Name>Hotel 4</Name>
    </Property>
    <Property>
        <Code>23423</Code>
        <Name>Hotel 5</Name>
    </Property>
</Agent>
<Agent ID="GHI789">
    <Property>
        <Code>45345</Code>
        <Name>Hotel 6</Name>
    </Property>
</Agent>
</XML>

I want to be able to output the above into the following format:

Agent | Code | Name
ABC123 | XYZ | Hotel 1
ABC123 | 237 | Hotel 2
......

How would I do this as there are multiple Agents and a varying amount of Properties within each Agent?

I have experience of using XMLReader but happy to try an alternative such as SimpleXML.

I think I would need to use a Foreach loop on this (Foreach Agent....) but not quite sure where to start.

Thanks!

Franco
  • 2,846
  • 7
  • 35
  • 54

1 Answers1

3

Look at this:

$sxe = new SimpleXMLElement($xmlstr);

echo 'Agent | Code | Name'.PHP_EOL;
foreach ( $sxe->Agent as $agent )
{
    $attr = $agent->attributes();

    foreach ( $agent->Property as $property )
    {
        echo $attr['ID'].' | '.$property->Code.' | '.$property->Name.PHP_EOL;       
    }
}
Piotr Olaszewski
  • 6,017
  • 5
  • 38
  • 65
  • Cool thank you, I'm using this to load the XML from a file: **$xmlstr = simplexml_load_file("test.xml");** but getting the error **Start tag expected, '<' not found in...**. Any ideas? The XML in the file is definitely valid – Franco Jun 28 '12 at 06:31
  • I copy-paste first XML, to new file and try `$xmlstr = simplexml_load_file("test.xml"); var_dump($xmlstr);` and everything is OK, I recived correct SimleXML object. – Piotr Olaszewski Jun 28 '12 at 06:47