PHP & # 8594; How can I check if XML is empty?

I get simple xml content from the request after a specific ID. But sometimes the identifier is no longer available, and the XML is empty.

How can I check with PHP if xml is empty?

If anyone has an idea, I would appreciate it if he could help me.

Thanks in advance.

Marco

+4
source share
5 answers

If you can use the SimpleXML extension:

$xmlObject = new SimpleXMLElement($xmlText); if ($xmlObject->count() == 0) { //it empty } else { //XML object has children } 

In addition, SimpleXML is a very convenient XML reader / editor.

Details: http://ua2.php.net/manual/en/book.simplexml.php

+6
source

I think it depends on what you mean by empty, if the whole document is empty, you can check if the empty version of the document is empty:

 if (empty($xmlString)) { // is empty } 

But if you are expecting a root node, you may 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 this helps.

+5
source

just use (string) before your id and it will work. example: - your code looks like this $ id = $ xml-> mail-> id;

then do it exactly the same $ id = (string) $ xml-> mail-> id;

he will work

+2
source

Just to add my two cents to the old question, but the most appropriate answer seems to involve using simplexml_load_file ("test.xml"); and then check that the node you expect is not empty. Since this will cause a warning level error if the file is empty, I would not agree and instead turned the call over using the file test.

 $xmlInfo = new SplFileInfo('test.xml'); if((int) $xmlInfo->getSize() > 0) { $xml = simplexml_load_file($xmlInfo->getPath()); } 

Of course, the OP asked How can I check with PHP if a xml is empty , which does not indicate whether it has a node value or a file, but for completeness it is.

+2
source

Try it:

 $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"; } 
0
source

Source: https://habr.com/ru/post/1438880/


All Articles