SyntaxStudy
Sign Up
PHP Loading XML from Files and URLs
PHP Intermediate 4 min read

Loading XML from Files and URLs

Loading XML Sources

SimpleXML can load XML from strings, files, or URLs. DOMDocument provides more control for complex XML operations.

Example
<?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;
    }
}
Pro Tip

Use libxml_use_internal_errors(true) before parsing untrusted XML to capture errors as an array rather than emitting warnings.