Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting empty XML node with PHP's SimpleXML

Let me start by saying I'm not well versed in parsing XML and/or writing PHP. I've been researching and piecing things together for what I'm working on, but I'm stuck.

I'm trying to create a basic if/else statement: if the node isn't empty, write the content of the node.

Here's a snippet of the XML I'm calling:

<channel>
    <item>
      <title>This is a test</title>
      <link />
      <description>Test description</description>
      <category>Test category</category>
      <guid />
    </item>
  </channel>

and here's the PHP I have so far:

<?php
    $alerts = simplexml_load_file('example.xml');
    $guid = $alerts->channel->item->guid;

    if ($guid->count() == 0) {
    print "// No alert";
}
    else {
        echo "<div class='emergency-alert'>".$guid."</div>";
}

?>

Obviously, "guid" is an empty node, but it's returning:

<div class="emergency-alert"> </div>

What am I doing wrong? :(

PS, I've tried hasChildren() and that didn't work either.

like image 645
Brittany Layne Rapheal Avatar asked Dec 12 '22 02:12

Brittany Layne Rapheal


1 Answers

@Wrikken is right. XPath is the preferred way of querying XML documents. But answering your question, in your simple case you can check if the node value is empty by casting SimpleXMLElement to string:

if ( !$guid->__toString() ) {
    print "No alert";
}
like image 126
Valentin Rodygin Avatar answered Dec 24 '22 20:12

Valentin Rodygin