Case
Occasionally check availability of a Google Merchant XML feed.
The feed is without DTD, so validate()
won't work.
Solution
// disable forwarding those load() errors to PHP
libxml_use_internal_errors(true);
// initiate the DOMDocument and attempt to load the XML file
$dom = new \DOMDocument;
$dom->load($path_to_xml_file);
// check if the file contents are what we're expecting them to be
// `item` here is for Google Merchant, replace with what you expect
$success = $dom->getElementsByTagName('item')->length > 0;
// alternatively, just check if the file was loaded successfully
$success = null !== $dom->actualEncoding;
length
above contains a number of how many products are actually listed in the file. You can use your tag names instead.
Logic
You can call getElementsByTagName()
on any other tag names (item
I used is for Google Merchant, your case may vary), or read other properties on the $dom
object itself. The logic stays the same: instead of checking if there were errors when loading the file, I believe actually trying to manipulate it (or specifically check if it contains the values you actually need) would be more reliable.
Most important: unlike validate()
, this won't require your XML to have a DTD.