dongzhan5286 2014-10-30 17:16
浏览 56
已采纳

使用PHP的SimpleXML检测空XML节点

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.

  • 写回答

3条回答 默认 最新

  • doqs8936 2014-10-30 18:23
    关注

    @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";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色