Read XML with like nodes PHP

1

I have the xml example:

<Listings>
    <Listing>
        <Title>Nome</Title>
        <Details>
            <Description>
                dados
            </Description>
        </Details>
        <Media>
            <Item medium="image">
                https://site.com.br/PM.jpeg
            </Item>
            <Item medium="image">
                https://site.com.br/PM.jpeg
            </Item>
            <Item medium="image">
                https://site.com.br/PM.jpeg
            </Item>
        </Media>
    </Listing>
        <Listing>
            <Title>Nome</Title>
            <Details>
                <Description>
                    dados
                </Description>
            </Details>
            <Media>
                <Item medium="image">
                    https://site.com.br/PM.jpeg
                </Item>
                <Item medium="image">
                    https://site.com.br/PM.jpeg
                </Item>
                <Item medium="image">
                    https://site.com.br/PM.jpeg
                </Item>
            </Media>
        </Listing>
</Listings>

I'm reading with the function simplexml_load_file , reading the data occurs normally, my problem is like reading all the items inside the <Media> I tried the following:

foreach($xml->Listings as $registro):
     echo 'Título: ' . $registro->Listing->Title . '<br>';

            foreach($registro->Listing->Media as $item):
                echo 'Imagem: ' . $item->Item . '<br>';
            endforeach;

endforeach;
    
asked by anonymous 30.08.2018 / 02:56

2 answers

3

The first element (called the root element) is <Listings> , that is, the object in $xml is already <Listings> , so there is no point in trying to get $xml->Listings , since $xml is already it.

It is also necessary to iterate <Items> inside <Media> , since it is more than one, then it has to use a loop, like foreach

The correct one would be:

$listings = simplexml_load_string($xml);

foreach ($listings as $listing):

    echo 'Título: ' . trim($listing->Title) . "<br>";

    foreach($listing->Media as $items):
        foreach($items as $item):
            echo 'Imagem: ' . trim($item) . "<br>";
        endforeach;
    endforeach;

endforeach;

Note that your xml returns spaces between urls, so with trim() you can eliminate unnecessary spacing.

    
30.08.2018 / 03:10
1

Good evening,

Try this here:

foreach($xml->Listings as $registro):
     echo 'Título: ' . $registro->Listing->Title . '<br>';

            foreach($registro->Listing->Media as $item):
            $loop = count($item);    

            for($i = 0; $i < $loop; $i++){
                    echo 'Imagem: ' . $item->Item[$i] . '<br>';
            }

            endforeach;

endforeach;
    
30.08.2018 / 03:08