Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

find and edit comment element of html with php

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';
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...