gpt4 book ai didi

php - 我正在尝试将数组转换为 XML,但未能 100% 正确

转载 作者:太空宇宙 更新时间:2023-11-03 11:25:07 25 4
gpt4 key购买 nike

我需要以 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。感谢所有帮助。谢谢。

最佳答案

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

使用 PHP 7.1.23 测试。输出:

<?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>

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

关于php - 我正在尝试将数组转换为 XML,但未能 100% 正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54994283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com