Kaal
Kaal

Reputation: 111

How do I loop through this array and call value/s?

I first had an XML file which I converted to the array that can be seen below. But the problem I am having is looping through the array and calling values. For instance, how would I loop through anime to get the anime name 'attack on titan' or start time, '9.30am' etc? How can I do this? Thank you.

Here's the array:

Array (
 [anime] => Array (
  [0] => Array (
   [id] => 1
    [content] => Array (
     [action_adventure_channel] => Array (
      [0] => Array (
       [name] => Array (
        [0] => Attach on Titan
        )
        [start_time] => Array (
         [0] => 09.30am
        )
        [end_time] => Array (
         [0] => 10.30am
        )
       )
      )
     )
    )
    [1] => Array (
     [id] => 2
     [content] => Array (
      [crime_drama_channel] => Array (
       [0] => Array (
        [name] => Array (
         [0] => Death Note
        )
        [start_time] => Array (
         [0] => 12.00pm
        )
        [end_time] => Array (
         [0] => 1.00pm
        )
       )
      )
     )
    )
   )
  )

EDIT: Here is the XML version that I converted to the above array:

<?xml version="1.0" encoding="UTF-8"?>
<anime_data>
    <anime id="1">
    <action_adventure_channel>
        <name>Attach on Titan</name>
        <start_time>09.30am</start_time>
        <end_time>10.30am</end_time>
    </action_adventure_channel>
    </anime>
    <anime id="2">
    <crime_drama_channel>
        <name>Death Note</name>
        <start_time>12.00pm</start_time>
        <end_time>1.00pm</end_time>
    </crime_drama_channel>
    </anime>
</anime_data>

Upvotes: 1

Views: 60

Answers (1)

Kevin
Kevin

Reputation: 41885

You could just use SimpleXML from the start. Then just traverse using foreach.

$xml = simplexml_load_file('path/to/xmlfile.xml');
foreach($xml as $anime) {
    $id = $anime->attributes()->id;
    foreach($anime as $info) {
        $name = $info->name;
        $start_time = $info->start_time;
        $end_time = $info->end_time;
    }
}

Sample Output

Upvotes: 1

Related Questions