2011-01-21 49 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

相關問題