问题
I'm trying to manipulate HTML codes by the use of simplehtmldom.sourceforge.net. This is i've got so far. I could create a new file or turn the index.html to index.php and copy the head tag from the index.html. The problem is, how could I insert the link tags:
<link href="style.css" rel="stylesheet" type="text/css" />
between the head tags?
<?php
# create and load the HTML
include('simple_html_dom.php');
// get DOM from URL or file
$html = file_get_html('D:\xampp\htdocs\solofile\index.html');
$indexFile ='index.php';
$openIndexFile = fopen($indexFile,'a');
//find head tag
foreach($html->find('head') as $e)
{
$findHead = $e->outertext;
fwrite($openIndexFile, "\n" .$findHead. "\n");
}
回答1:
From the documentation (Section : How to access the HTML element's attributes? / Tips) :
// Append a element
$e->outertext = $e->outertext . '<div>foo<div>';
Which you may use like this :
$e = $html->find('head')->innertext; // Should take all HTML inside <head></head> w/o <head></head
$e = $e.'<link href="style.css" rel="stylesheet" type="text/css" />'; // inserting the CSS at the end of what's inside <head></head>
I didn't try but maybe (depending on the class) you may need to make the first line into 2.
$f = $html->find('head');
$e = $f->innertext;
But you get the idea, right? ;)
来源:https://stackoverflow.com/questions/4755570/how-to-insert-link-tags-between-head-tags-on-html-using-simplehtmldom