Search code examples
phpxmlsimplexml

How to read specific amounts of code in a SimpleXMLElement


I'm trying to read a part of a SimpleXMLElement/XML file. The problem is I can't get the desired text anyway I try.

I tried debugging the XML I had, so I printed it this way:

 foreach($response->items as $item) {
                   fwrite($file, var_export($item, TRUE));
               }

which outputs

SimpleXMLElement::__set_state(array( 'item' => array ( 0 => SimpleXMLElement::__set_state(array( 'id' => '000-1', 'description' => 'Notebook Prata', 'quantity' => '1', 'amount' => '1830.00', )), 1 => SimpleXMLElement::__set_state(array( 'id' => 'AB01', 'description' => 'Notebook Preto', 'quantity' => '2', 'amount' => '1340.00', )), ), ))

But when I try to retrieve the data inside the specific items, the return is empty. I tried the following:

fwrite($file, $item->amount);
//
fwrite($file, $item->{'amount'});
//
fwrite($file, $items->$item->amount);

But nothing seems to work.

How can I correct the syntax, to obtain the expected? I would want the file to have written '1830.00' and '1340.00', but I only get blanks.

XML LIKE THIS FOR REFERENCE


Solution

  • You have been fooled by the fact that this seems logical if you read it in English:

    foreach($response->items as $item) {
    

    But it doesn't match the structure of the XML.

    Consider this XML:

    <?xml version="1.0"?><a>
        <b>
            <c>first C</c>
            <c>second C</c>
        </b>
    </a>
    

    If $response is the whole document (<a>...</a>), then to access each <c>, you need to do this:

    foreach($response->b->c as $c)
    

    Your XML has this same structure:

    <?xml version="1.0"?><transaction>
        ...
        <items>
            <item>first item</item>
            <item>second item</item>
        </items>
        ...
    </transaction>
    

    So your loop needs to be:

    foreach($response->items->item as $item)
    

    Then the children of <item> will be available as you expected, such as the <amount>:

    echo $item->amount;