【问题标题】:How to check the existence of any HTML element using a PHP condition?如何使用 PHP 条件检查任何 HTML 元素是否存在?
【发布时间】:2018-05-31 02:50:21
【问题描述】:

在 WordPress 网站上,如何使用 PHP 条件检查任何 HTML 元素(带有 ID 或类)是否存在?

此票证解决方案不适用于我的情况。 Check if div ID exists in PHP

无论如何,我已经尝试过使用此代码:

$new = $html->find("#banner_id");
if($new){
    echo "Exists";
} else {
    echo "Not Exists";
}

但这导致了以下错误:

【问题讨论】:

  • 所以您的 $html 变量为空,而不是对象。你是如何创造它的?你期待它是什么?
  • 其实,我不确定这个 $html 变量,我以为它会预先定义任何对象或任何东西!这就是为什么没有对此进行调查。无论如何,我现在应该怎么做才能让它工作?谢谢
  • 这并没有解决我的问题。

标签: php html wordpress if-statement conditional


【解决方案1】:

我发现你的 $html 变量是 null 你需要在开始通过 id 查找元素之前创建对象

 $html = new simple_html_dom(); // Create a DOM object
 Method - 1:  $html->load_file('path-to-file/example.html');   // Load HTML from a HTML file   
 Method - 2:  $html->load_file('http://www.yourdomainname.com/');// Load HTML from an URL
 Method - 3:  $html->load('<html><body><div id="banner_id">All the Besttttt!</div></body></html>'); // Load HTML from a string

使用以上列表中的任何方法然后开始查找。

$main = $html->find('div[id=banner_id]',0);// Find the element where the id is equal to a particular value

完整代码


$html->load('<html><body><div id="banner_id">All the Besttttt!</div></body></html>');// Load HTML from a string
$divdata= $html->find('div[id=banner_id]',0);// Find the element where the id is equal to a particular value

更多详情请看这里http://www.gurutechnolabs.com/php-simple-html-dom-parser-script/

【讨论】:

  • 您好,可能是我无法以正确的方式使用它,或者该过程无法正常工作。我使用了以下代码,然后又遇到了另一个错误。 $html = new simple_html_dom(); $html-&gt;load('&lt;html&gt;&lt;body&gt;&lt;div class="div2"&gt;&lt;a id="banner"&gt;Sample Link&lt;/a&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;'); $divdata= $html-&gt;find('a[id=banner]',0); 错误:Fatal error: Uncaught Error: Class 'simple_html_dom' not found in /home/showhan/sites/public_html/phplearning/index.php:30 Stack trace: #0 {main} thrown in /home/showhan/sites/public_html/phplearning/index.php on line 30
  • 是的,发现没有包含 simpl_html_dom 文件,只需在此处下载该文件形式 sourceforge.net/projects/simplehtmldom/?source=typ_redirect 并包含它,希望这能解决您的问题
猜你喜欢
  • 1970-01-01
  • 2011-03-22
  • 2019-10-02
  • 1970-01-01
  • 2016-08-05
  • 2016-05-27
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
相关资源
最近更新 更多