Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP -> How can I check if a XML is empty

Tags:

php

xml

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

like image 757
Artpixler Avatar asked Oct 10 '12 12:10

Artpixler


5 Answers

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

like image 118
SlyChan Avatar answered Oct 12 '22 19:10

SlyChan


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.

like image 24
Sol Avatar answered Oct 12 '22 18:10

Sol


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

like image 32
Shivam Avatar answered Oct 12 '22 20:10

Shivam


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.

like image 2
user2481985 Avatar answered Oct 12 '22 20:10

user2481985


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";
}
like image 1
AdoboFlush Avatar answered Oct 12 '22 19:10

AdoboFlush