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.
@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";
}
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