Question

I'm trying to loop multiple items from an XML with the code below.

$xml = get_data('the-url');
$data = simplexml_load_string($xml);

foreach($data->item AS $item) {
    foreach($item AS $test) {
        var_dump($test);
    }
}

The XML looks like this:

<xml>
    <item>
        <name>...</name>
        <chapter>...</chapter>
        <text>
            ...
        </text>
    </item>
    <item>
        <name>...</name>
        <chapter>...</chapter>
        <text>
            ...
        </text>
    </item>
    <item>
        <name>...</name>
        <chapter>...</chapter>
        <text>
            ...
        </text>
    </item>
    <item>
        <name>...</name>
        <chapter>...</chapter>
        <text>
            ...
        </text>
    </item>
    <item>
        <name>...</name>
        <chapter>...</chapter>
        <text>
            ...
        </text>
    </item>
</xml>

As it is right now, the var_dump($test) prints this:

object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { }
object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { }
object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { }
object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { }
object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { }
object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { }
object(SimpleXMLElement)#7 (0) { } object(SimpleXMLElement)#8 (0) { } ...

What should I do to make my code to loop all the items and prints the value?

Was it helpful?

Solution

Try this:

$xml_content = file_get_contents('http://url/feed.xml');
$data = simplexml_load_string($xml_content);

foreach ($data->item as $item) {
    var_dump($item->bookname);
}

You can also cast whole $item to array if you need:

foreach ($data->item as $item) {
    $itemArray = (array) $item;
    var_dump($itemArray);
}

You were dumping objects, when you need to cast the to string first to return the text value. Also, I do not think the second foreach was doing anything or needed, so I removed it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top