Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...