用php查找和编辑html的注释元素 [英] find and edit comment element of html with php

查看:80
本文介绍了用php查找和编辑html的注释元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编辑以下评论标签的内部,以便我可以更改css文件的位置。这需要通过PHP完成。

评论部分:

 <! -  [if IE 6]>< link rel =stylesheettype =text / csshref =/ Css / IE6.cssmedia =screen/> ;< ENDIF]  -  GT!; 

不起作用的代码:

  $ csslist = $ xpath-> query(//<! -  [if IE 6]>); 
foreach($ csslist as $ css){
$ css-> innertext ='test';


解决方案

试试

  libxml_use_internal_errors(TRUE); 
$ dom = new DOMDocument;
$ dom-> loadHTMLFile('http://www.nytimes.com/');
libxml_clear_errors();

$ xpath = new DOMXPath($ dom);
foreach($ xpath-> query('// comment()[contains(。,link)]')as $ node)
{
var_dump($ node-> ;数据);
}

这将给出:

  string(135)[if IE]> 
< link rel =stylesheettype =text / csshref =http:// graphics8 (138)[if IE 6] .ytimes.com / css / 0.1 / screen / build / homepage / ie.css>
<![endif]

string(138) >
< link rel =stylesheettype =text / csshref =http://graphics8.nytimes.com/css/0.1/screen/build/homepage/ie6.css>
<![endif]

正如您所看到的,实际的评论节点是只是<! - - > 部分。其余的只是文字。 [如果IE]> 不是实际标签的一部分。这是字符数据。


I need to edit the inside of the following comment tag so that I can change the location of the css file. This needs to be done through PHP. I have tried using the following code but I get invalid expression errors.

Comment Section:

<!--[if IE 6]><link rel="stylesheet" type="text/css" href="/Css/IE6.css" media="screen" /><![endif]-->

Code that does not work:

    $csslist = $xpath->query("//<!--[if IE 6]>");    
foreach($csslist as $css) {                 
    $css->innertext = 'test';
}

解决方案

Try "//comment()" to get all CommentNodes.

Note that the link element in the CommentNode is not a childNode of the commentNode but mere data:

libxml_use_internal_errors(TRUE);
$dom = new DOMDocument;
$dom->loadHTMLFile( 'http://www.nytimes.com/' );
libxml_clear_errors();

$xpath = new DOMXPath($dom);
foreach( $xpath->query('//comment()[contains(., "link")]') as $node)
{
   var_dump( $node->data );
}

This will give:

string(135) "[if IE]>
    <link rel="stylesheet" type="text/css" href="http://graphics8.nytimes.com/css/0.1/screen/build/homepage/ie.css">
<![endif]"

string(138) "[if IE 6]>
    <link rel="stylesheet" type="text/css" href="http://graphics8.nytimes.com/css/0.1/screen/build/homepage/ie6.css">
<![endif]"

As you can see, the actual comment node is just the <!-- and --> parts. The remainder is just text. The [if IE]> is not part of the actual tag. It is character data.

这篇关于用php查找和编辑html的注释元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆