0

I am trying to convert xml into php array but somehow i am doing a mistake, can anyone please help me ?

Here the xml formate :

<Department Id="3">
    <Week Date="23/03/2020">
        <Class DateTime="23/03/2020 18:00"/>
        <Class DateTime="23/03/2020 18:45"/>
    </Week>
    <Week Date="30/03/2020">
        <Class DateTime="30/03/2020 18:00"/>
        <Class DateTime="30/03/2020 18:45"/>
    </Week>
</Department>

Output Need like this :

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [DateTime] => 23/03/2020 18:00
                )
            [1] => Array
                (
                    [DateTime] => 23/03/2020 18:45
                )
        )
    [1] => Array
        (
            [0] => Array
                (
                    [DateTime] => 30/03/2020 18:00
                )
            [1] => Array
                (
                    [DateTime] => 30/03/2020 18:45
                )
        )   
)

This is what i have tried

foreach ($xml->children() as $week) {
    foreach ($week->children() as $class) {
        $j = 0;
        foreach ($class->attributes() as $a => $b){
            $results[$i][$j][$a] = (string) $b;
        }
        $j++;
    }
    $i++;
}

I dont know whats wrong in my code :(

1 Answer 1

1

It's just a case of getting the right levels in the XML to match the loops, this builds a weeks data at a time and adds it into the overall results...

$results = [];
foreach ( $xml->Week as $week ) {
    $weekData = [];
    foreach ( $week->Class as $class )  {
        $weekData[]['DateTime'] = (string)$class['DateTime'];
    }
    $results[] = $weekData;
}

To make this load all attributes...

$results = [];
foreach ( $xml->Week as $week ) {
    $weekData = [];
    foreach ( $week->Class as $class )  {
        $classData = [];
        foreach ( $class->attributes() as $name => $value )   {
            $classData[$name] = (string)$value;
        }
        $weekData[] = $classData;
    }
    $results[] = $weekData;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. Just a question if i have more than attributes like DateTime, how will fetch it dynamically ??
I've added some updated code which adds all attributes of the Class element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.