Parse XML with SimpleXML
Parses an XML string with SimpleXML, reports parsing errors, and extracts selected child values into an array.
Purpose
Parses an XML string with SimpleXML, reports parsing errors, and extracts selected child values into an array.
Snippet details
ContextFileLevelProductionCopy-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.
*/
/**
* Parse XML with SimpleXML.
*
* Purpose:
* Parses a small XML payload, handles libxml errors cleanly, and converts a
* known set of child nodes into a plain PHP array.
*
* @param string $xml_text XML payload to parse.
* @return array Parse status, errors, and extracted mission data.
*/
function ogSnippetParseXmlWithSimplexml(string $xml_text): array {
$xml_text = trim($xml_text);
if ($xml_text === '') {
return array('success' => false, 'errors' => array('XML text is required.'), 'mission' => array());
}
$previous_setting = libxml_use_internal_errors(true);
libxml_clear_errors();
$xml = simplexml_load_string($xml_text, 'SimpleXMLElement', LIBXML_NONET);
$errors = libxml_get_errors();
libxml_clear_errors();
libxml_use_internal_errors($previous_setting);
if ($xml === false) {
$messages = array();
foreach ($errors as $error) {
$messages[] = trim($error->message).' on line '.$error->line;
}
if (count($messages) < 1) {
$messages[] = 'XML could not be parsed.';
}
return array('success' => false, 'errors' => $messages, 'mission' => array());
}
$callsign = '';
$sector = '';
$status = '';
if (isset($xml->callsign) === true) {
$callsign = trim((string) $xml->callsign);
}
if (isset($xml->sector) === true) {
$sector = trim((string) $xml->sector);
}
if (isset($xml->status) === true) {
$status = trim((string) $xml->status);
}
$mission = array(
'callsign' => $callsign,
'sector' => $sector,
'status' => $status
);
return array('success' => true, 'errors' => array(), 'mission' => $mission);
}
/*
$xml = '<mission><callsign>Galactica</callsign><sector>Cyrannus</sector><status>Condition One</status></mission>';
$result = ogSnippetParseXmlWithSimplexml($xml);
print_r($result);
*/