2011-01-21 50 views
3

我想通过使用simplehtmldom.sourceforge.net来操纵HTML代码。这是我迄今为止。我可以创建一个新文件或将index.html改为index.php并从index.html复制头标记。问题是,我怎样才能插入链接标签:如何使用SimpleHtmlDom在HTML头标签之间插入链接标签

<link href="style.css" rel="stylesheet" type="text/css" /> 

之间的头标签?

<?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"); 
} 

回答

7

documentation(节:如何访问HTML元素的属性/提示):

// Append a element 
$e->outertext = $e->outertext . '<div>foo<div>'; 

,你可以使用这样的:

$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> 

我没有尝试但可能(取决于班级)你可能需要将第一行变成2.

$f = $html->find('head'); 
$e = $f->innertext; 

但你明白了吧? ;)

+0

+1 for spoonryeding – Gordon 2011-01-21 10:48:32

相关问题