Simple XML Creation
Creates a small XML document with SimpleXMLElement, adds child nodes and attributes, and returns the XML string.
Purpose
Creates a small XML document with SimpleXMLElement, adds child nodes and attributes, and returns the XML string.
Snippet details
ContextXmlLevelPracticalCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Simple XML Creation.
*
* Purpose:
* Creates a small XML document with child elements and attributes.
*
* @param array $mission Mission data for the XML document.
* @return string XML document string.
*/
function ogSnippetSimpleXmlCreation(array $mission): string {
$title = '';
$ship = '';
$status = '';
if (isset($mission['title']) === true && is_scalar($mission['title']) === true) {
$title = trim((string) $mission['title']);
}
if (isset($mission['ship']) === true && is_scalar($mission['ship']) === true) {
$ship = trim((string) $mission['ship']);
}
if (isset($mission['status']) === true && is_scalar($mission['status']) === true) {
$status = trim((string) $mission['status']);
}
if ($title === '') {
$title = 'Untitled Mission';
}
if ($ship === '') {
$ship = 'Unknown Ship';
}
if ($status === '') {
$status = 'pending';
}
$xml = new SimpleXMLElement('<mission></mission>');
$xml->addAttribute('status', $status);
$xml->addChild('title', htmlspecialchars($title, ENT_XML1 | ENT_COMPAT, 'UTF-8'));
$xml->addChild('ship', htmlspecialchars($ship, ENT_XML1 | ENT_COMPAT, 'UTF-8'));
$xml_output = $xml->asXML();
if ($xml_output === false) {
return '';
}
return $xml_output;
}
$mission_xml = ogSnippetSimpleXmlCreation(array(
'title' => 'LV-426 survey',
'ship' => 'Sulaco',
'status' => 'active'
));
echo $mission_xml;