I get simple xml content from a request after a certain ID. But sometimes an ID isn't anymore available and the XML is empty.
How can I check with PHP if a xml is empty?
If someone has an idea I would appreciate if he could help me.
Thanks in advance.
Marco
If you can use SimpleXML extention:
$xmlObject = new SimpleXMLElement($xmlText);
if ($xmlObject->count() == 0) {
//it's empty
}
else {
//XML object has children
}
Also, SimpleXML is a very handy XML-reader/editor.
Details: http://ua2.php.net/manual/en/book.simplexml.php
I guess it depends on what you mean by empty, if the entire document is empty, you can check if the string version of the document is empty with:
if (empty($xmlString))
{
// is empty
}
But if you're expecting a root node, you might need to check if there are any children:
$xml = simplexml_load_file("test.xml");
if (empty($xml->getName()) && count($xml->children()) == 0) {
// is empty
}
Hope that helps.
just use (string) before your id and it will work. example:- your code is like this $id = $xml->mail->id;
then make it just like this $id = (string)$xml->mail->id;
it will work
Just to add my two cents to an old question, but the top rated answer seems to suggest using simplexml_load_file("test.xml"); and then testing that a node you expect is not empty. As this would thrown a warning level error if the file is empty, I would disagree and instead wrap the call with a test for filesize.
$xmlInfo = new SplFileInfo('test.xml');
if((int) $xmlInfo->getSize() > 0)
{
$xml = simplexml_load_file($xmlInfo->getPath());
}
Of course OP has asked How can I check with PHP if a xml is empty
, which doesn't specify if he means node or file, but for completeness there it is.
Try This:
$xml_str = '<?xml version="1.0" standalone="yes"?><Name/>';
$xml = new SimpleXMLElement($xml_str);
if(empty($xml->Name[0])){
// ITS EMPTY !! DO SOMETHING
echo "ITS EMPTY ASJK";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With