简体   繁体   English

使用 PHP 的 DOMDocument 解析 html 内容时出错

[英]Error in parsing html content using DOMDocument of PHP

Can anyone please help me in finding out what have I done wrong in the code given below.任何人都可以帮助我找出我在下面给出的代码中做错了什么。

I have a PHP variable named news_content whose value is the following html...我有一个名为news_content的 PHP 变量,其值是以下 html...

<p><img src="./images/image1.jpeg" alt=""></p>

This value for variable news_content is obtained from a database query.变量news_content 的这个值是从数据库查询中获得的。

The function below creates a DOMDocument object using the variable news_content :下面的函数使用变量news_content创建一个 DOMDocument 对象:

public function convert_to_tinymce_data($news_content)
{
    $dom=new DOMDocument();

    $dom->loadHTML($news_content);

    $img_nodes=$dom->getElementsByTagName('img');

    foreach($img_nodes as $link)
    {
        $img_link=$link->getAttribute('src');

        echo $link->getAttribute('src');

    }
}

But nothing is being echoed (receiving a blank page).但没有任何回应(收到空白页)。

I've tryed this code and it works:我已经尝试过这个代码并且它有效:

$n = '<p><img src="./images/image1.jpeg" alt=""></p>';

function convert_to_tinymce_data($news_content){
 $dom=new DOMDocument();

 $dom->loadHTML($news_content);
 $img_nodes=$dom->getElementsByTagName('img');

 foreach($img_nodes as $link) {
        $img_link=$link->getAttribute('src');
        echo $img_link;
  }
}

convert_to_tinymce_data($n);

I see you have public function , but I don't see class.我看到你有public function ,但我没有看到 class。 If it's global function, not a method of a class, that's the reason why it doesn't work.如果它是全局函数,而不是类的方法,那就是它不起作用的原因。 Or you don't call function properly.或者你没有正确调用函数。

(What you have there is function definition... it executes after you call it... Having same variable names in your function's definition and outside is bad practice and can be easily turn into problem) (你所拥有的是函数定义......它在你调用它后执行......在你的函数定义和外部具有相同的变量名是不好的做法,很容易变成问题)

Just to add: Check you're error_log file and let us know is there something interesting in it...只是添加:检查您的 error_log 文件,让我们知道其中是否有一些有趣的东西...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM