MMelvin0581
MMelvin0581

Reputation: 503

I'm trying to convert an array to XML but I am failing to get it 100% correct

I need to output the response from the database in XML. So far I have gotten it to output this:

enter image description here

The outermost tag needs to match the name of the action query, it'll either be <courses> or <students>.

Here is my code:

<?php
require_once('./database.php');

if (isset($_GET['format'])) {
    $format = filter_var($_GET['format']);
}

if (isset($_GET['action'])) {
    $action = filter_var($_GET['action'], FILTER_SANITIZE_STRING);
    $tableName = "sk_$action";
}

$query = "SELECT * FROM $tableName";

if (isset($_GET['course'])) {
    $course = filter_input(INPUT_GET, 'course');
    $query .= " WHERE courseID = :course";
}

function arrayToXml($arr, $i = 1, $flag = false)
{
    $sp = "";
    for ($j = 0; $j <= $i; $j++) {
        $sp .= " ";
    }
    foreach ($arr as $key => $val) {
        echo "$sp&lt;" . $key . "&gt;";
        if ($i == 1) echo "\n";
        if (is_array($val)) {
            if (!$flag) {
                echo "\n";
            }
            arrayToXml($val, $i + 5);
            echo "$sp&lt;/" . $key . "&gt;\n";
        } else {
            echo "$val" . "&lt;/" . $key . "&gt;\n";
        }
    }

}

$statement = $db->prepare($query);
$statement->bindValue(':course', $course);
$statement->execute();

$response = $statement->fetchAll(PDO::FETCH_ASSOC);

$statement->closeCursor();

if ($format == 'json') {
    echo json_encode($response);
}
if ($format == 'xml') {
    arrayToXml($response, 1, true);
}

I'm pretty new to PHP and have never worked with XML. All help is appreciated. Thanks.

Upvotes: 0

Views: 47

Answers (1)

Bill Karwin
Bill Karwin

Reputation: 562771

function arrayToXml($arr, $collectionTag, $singleTag) {
    $collection = new SimpleXMLElement("<$collectionTag/>");
    foreach ($arr as $row) {
        $element = $root->addChild($singleTag);
        foreach ($row as $tag => $value) {
            $element->addChild($tag, $value);
        }
    }
    return $collection;
}

$courses = arrayToXml($response, 'courses', 'course');

echo $courses->asXML();

Tested with PHP 7.1.23. Output:

<?xml version="1.0"?>
<courses>
 <course><courseID>cs601</courseID><courseName>Web Application Development</courseName></course>
 <course><courseId>cs602</courseId><courseName>Server-Side Application Development</courseName></course>
 <course><courseId>cs701</courseId><courseName>Rich Internet Application Development</courseName></course>
</courses>

(I added newlines because by default it doesn't add any.)

Upvotes: 3

Related Questions