Writing a php file to update HTML in web page
I need to write a php file that I can 'include' in a web page. When I include the file on any page, I need it to parse the HTML in the page and add a new CSS class to all img elements in the page.
The question is, 开发者_运维问答my friends, is this at all possible? Bear in mind, I want to be able to do this to many pages by simply including my php file.
Thanks!!!
Does this have to be done with PHP on the server side? Because it's easier to accomplish with Javascript on the client side, since they HTML is already formed. You can include this block of javascript
// Plain javascript example
function addImgClass() {
var images = document.getElementsByTagName("img");
var numImg = images.length;
for (var i=0; i<numImg; i++) {
images[i].className = images[i].className + " " + "your-new-CSS-class";
}
}
<!-- add to your html -->
<body onload="addImgClass();">
etc. etc.
Or if you are already using jQuery, it's even easier still. Other Javascript frameworks can accomplish the same with slightly different syntax if you happen to have Dojo or Prototype available for use.
// jQuery example
$(document).ready(function() {
$("img").addClass("your-new-CSS-class");
});
Yes and no.
No, because you cannot simply include a php file in your page and have it process other content... it is not possible as the HTML content will not be processed by PHP, but output directly.
Yes, you can do that indirectly: e.g. load the HTML into a DOM document in PHP, modify it, and output the resulting structure.
However, as mentioned by Michael, this is better done client-side by Javascript... with the advantage that you will work on the final, formed HTML; the (only) disadvantage being that if JS is disabled (very improbable these days, though) it will not work.
This is easily possible, and one of the great things about PHP. One thing to bear in mind, however, is that if the file you're including another file into is a .html
file, it won't be parsed by PHP so the include
won't be found; make sure all your files are .php
, with the appropriate headers set for each, if it's a CSS file say.
As @Michael has pointed out in the comments, you can tell the PHP parser to look through .html
files, however it's better practice to only get it to parse native .php
files.
精彩评论