I’m trying to build an XML file using PHP and pull data from my MySQL database through PDO. I have a database table called Categories that stores different category names like Travel, Education, etc. My goal is to create XML elements for each category dynamically.
<?php
$document = new DomDocument("1.0", "UTF-8");
session_start();
require("database.php");
$currentUser = $_SESSION['username'];
$mainReport = $document->createElement("Report");
$mainReport = $document->appendChild($mainReport);
$monthlyData = $document->createElement("MonthlyData");
$monthlyData = $mainReport->appendChild($monthlyData);
$query = $database->prepare("SELECT Amount FROM Transactions WHERE TransactionType='Expense' AND UserID = (SELECT UserID FROM Members WHERE Username = '$currentUser')");
$query->execute();
$amounts = $query->fetchAll(PDO::FETCH_ASSOC);
$grandTotal = 0;
foreach ($amounts as $record) {
$grandTotal = $grandTotal + $record["Amount"];
}
echo "$grandTotal";
$categoryQuery = $database->prepare("SELECT categoryTitle FROM ExpenseCategories WHERE UserID = (SELECT UserID FROM Members WHERE Username = '$currentUser')");
$categoryQuery->execute();
$categories = $categoryQuery->fetchAll();
foreach ($categories as $record) {
echo "<div>" . $record['categoryTitle'] . "</div>";
$categoryNode = $document->createElement($record['categoryTitle']);
$categoryNode = $monthlyData->appendChild($categoryNode);
$amountNode = $document->createElement("Amount", "$150");
$amountNode = $categoryNode->appendChild($amountNode);
}
$totalSection = $document->createElement("TotalSection");
$totalSection = $monthlyData->appendChild($totalSection);
$finalAmount = $document->createElement("Amount", '$grandTotal');
$finalAmount = $totalSection->appendChild($finalAmount);
$document->formatOutput = true;
$xmlContent = $document->saveXML();
$document->save("report.xml");
?>
The issue I’m facing is that when I try to add the calculated total value to the XML elements, it doesn’t seem to work properly. The calculation part works fine but inserting that value into the XML structure is giving me trouble. Any suggestions would be really helpful!