【问题标题】:Checking if div contains p element with php用php检查div是否包含p元素
【发布时间】:2017-12-04 00:17:48
【问题描述】:

我想知道是否可以通过 php 查看父元素是否有子元素?我知道使用 jQuery 是可能的,但我需要使用 php 来完成,因为我需要检查是否根据该子元素的存在以不同方式显示我的内容。

我现在拥有的是:

<?php if ($showLeftColumn) : ?>
            <aside class="sppb-col-md-3 custom-style-left">
                <jdoc:include type="modules" name="left-top" style="xhtml" />
                <jdoc:include type="modules" name="left-center" style="xhtml" />
                <jdoc:include type="modules" name="left-bottom" style="xhtml" />
            </aside>
        <?php endif; ?>

这现在可以工作,但它仍然显示为空,因为该位置是按标准加载的。我想要的是,如果位置被加载,那么它会进入第一个 if 然后检查子元素是否存在于父元素中。

有谁知道这是否可能通过获取 dom 结构或其他更简单的方法来实现?

【问题讨论】:

  • 不太确定你要做什么(代码不包含任何 p,只有一个 if),但如果你想使用 PHP 解析 DOM,请尝试 PHP 的 DOMDocument
  • 嗯,是的,你是对的......我的问题很模糊,但感谢遮阳篷! if 语句检查是否必须加载左上角位置。我已将其设置为 true,以便加载它,但是当它加载时,它加载到包含 p 元素的文章中,我想检查它是否包含该 p 元素,因为有时不会有文章,但位置必须始终是已加载。

标签: php html dom joomla


【解决方案1】:

以下应该可以解决您的问题。

<?php
        $content = '<aside class="sppb-col-md-3 custom-style-left">
                            <jdoc:include type="modules" name="left-top" style="xhtml" />
                            <jdoc:include type="modules" name="left-center" style="xhtml" />
                            <jdoc:include type="modules" name="left-bottom" style="xhtml" />
                        </aside>';
        if (strpos($content, '<p') === false) {
          //Don't show content, maybe show something else?
        } else {
          echo $content;
        } ?>

【讨论】:

    【解决方案2】:

    请允许我重新表述您的问题。你的方法是先制造一个问题(创建空的side),然后清理它(找出aside是否是空的),同时你也可以一起避免这个问题。

    Joomla 提供了countModules() 方法,它允许您使您的代码依赖于即将发生的事情。然后您可以将代码重写为

    <?php if (($showLeftColumn) &&
            ($this->countModules("left-top") + 
             $this->coutnModules("left-center") +
             $this->countModules("left-bottom"))): 
    ?>
            <aside class="sppb-col-md-3 custom-style-left">
                <jdoc:include type="modules" name="left-top" style="xhtml" />
                <jdoc:include type="modules" name="left-center" style="xhtml" />
                <jdoc:include type="modules" name="left-bottom" style="xhtml" />
            </aside>
        <?php endif; ?>
    

    【讨论】:

    • 嗯,这似乎使整个网站不再加载?我会认为它会起作用吗?
    • 如果您的网站不再加载,最可能的原因是 PHP 代码中的语法错误。如果您只是复制粘贴代码,那么您还复制了我无意中的错字:在第二个实例中是 coutnModules 而不是 countModules。 -- 对不起
    猜你喜欢
    • 1970-01-01
    • 2012-01-25
    • 2016-05-24
    • 2016-10-13
    • 2013-07-31
    • 2017-11-24
    • 2021-07-16
    • 1970-01-01
    • 2011-09-25
    相关资源
    最近更新 更多