如何使用SimpleHtmlDom在HTML标题上的头标记之间插入链接标记

时间:2011-01-21 05:04:37

标签: php html-parsing

我正在尝试使用simplehtmldom.sourceforge.net来操纵HTML代码。这是我到目前为止。我可以创建一个新文件或将 index.html 转换为 index.php 并从index.html复制head标记。问题是,我怎么能插入链接标签:

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

1 个答案:

答案 0 :(得分: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;

但是你明白了,对吗? ;)

相关问题