我正在尝试将数组转换为XML,但无法100%正确地进行

时间:2019-03-05 01:50:00

标签: php mysql xml

我需要以XML输出来自数据库的响应。到目前为止,我已经得到了输出:

enter image description here

最外面的标记需要与操作查询的名称匹配,它应该是<courses><students>

这是我的代码:

<?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);
}

我对PHP还是很陌生,从未使用过XML。感谢所有帮助。谢谢。

1 个答案:

答案 0 :(得分:3)

// Input = Product: My wonderful product.
// Output = My wonderful product
const text = 'Product: My wonderful product.';
const product = 'PRODUCT: ';

const matches = text.match(new RegExp(`(?:${product})(.*)`, 'i'));

let result;
if (matches && matches.length === 2) {
  result = matches[1];
} else {
  result = '';
}

console.log(result)

使用PHP 7.1.23测试。输出:

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();

(我添加了换行符,因为默认情况下它不添加任何换行符。)