Loading XML Sources
SimpleXML can load XML from strings, files, or URLs. DOMDocument provides more control for complex XML operations.
SimpleXML can load XML from strings, files, or URLs. DOMDocument provides more control for complex XML operations.
<?php
// From string
$xml = simplexml_load_string($xmlString);
// From file
$xml = simplexml_load_file("/path/to/file.xml");
// From URL (e.g., RSS feed)
$feed = simplexml_load_file("https://example.com/feed.rss");
foreach ($feed->channel->item as $item) {
echo (string)$item->title . "
";
echo (string)$item->link . "
";
}
// Error handling
libxml_use_internal_errors(true);
$xml = simplexml_load_string($input);
if ($xml === false) {
foreach (libxml_get_errors() as $error) {
echo $error->message;
}
}
Use libxml_use_internal_errors(true) before parsing untrusted XML to capture errors as an array rather than emitting warnings.