繁体   English   中英

DOM操作

[英]DOM manipulation

我试图在PHP中使用DOM做一个非常具体的工作,到目前为止我没有运气,目的是从Wordpress博客文章中获取一串HTML(来自DB,这是一个wordpress插件)。 然后从该HTML替换<div id="do_not_edit">old content</div>"并在其位置使用<div id="do_not_edit">new content</div>" 在结构中保存div上方和下方的任何内容。

然后将HTML保存回数据库,应该很简单,我已经读过正则表达式不是正确的方法,所以我转而使用DOM。

问题是我不能让它工作,不能提取div或任何东西。

帮我!!

UPDATE

来自wordpress表的HTML看起来像:

Congratulations on finding us here on the world wide web, we are on a  mission to create a website that will show off your culinary skills  better than any other website does.

<div id="do_not_edit">blah blah</div>
We want this website to be fun and  easy to use, we strive for simple elegance and incredible functionality.We aim to provide a 'complete package'. By this we want to create a  website where people can meet, share ideas and help each other out.

经过几次不同(不正确)的工作后,我得到的是:

$content = ($wpdb->get_var( "SELECT `post_content` FROM $wpdb->posts WHERE ID = {$article[post_id]}" ));        

$doc = new DOMDocument();
$doc->validateOnParse = true; 
$doc->loadHTMLFile($content);
$element = $doc->getElementById('do_not_edit');
echo $element;

如果您确定WordPress中的HTML只包含一个div,则以下内容应该有效:

$doc = new DOMDocument();
$doc->validateOnParse = false; 
$doc->loadHTML($content);
$divs = $doc->getElementsByTagName('div');
echo $divs->item(0)->textContent;

如果没有,请尝试:

$doc = new DOMDocument();
$doc->validateOnParse = false; 
$doc->loadHTML($content);
$divs = $doc->getElementsByTagName('div');

for($i=0; $i<$divs->length; $i++)
{
  $id = $divs->item($i)->attributes->getNamedItem('id');
  if($id && $id->value == 'do_not_edit')
  {
    //your code here...
    $node = $divs->item($i);
    $newText = new DOMText("This is some new content");

    $node->appendChild($newText);
    $node->removeChild($node->firstChild);
    break;
  }
}

$html = $doc->saveHTML();

您的HTML不是一个完整的HTML文档,这是DOMDocument所期望的。 一种选择是包装你的HTML,这是一个完整的文档:

$content = ($wpdb->get_var( "SELECT `post_content` FROM $wpdb->posts WHERE ID = {$article[post_id]}" ));

$content = '<html><head><title></title></head><body>'.$content.'</body></html>';

$doc = new DOMDocument();
$doc->validateOnParse = false; 
$doc->loadHTML($content);
$element = $doc->getElementById('do_not_edit');
echo $element;

这有点hacky,但可能很容易解决问题。

暂无
暂无

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

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