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

won*_*ana 3 php html-parsing

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

<link href="style.css" rel="stylesheet" type="text/css" />
Run Code Online (Sandbox Code Playgroud)

头部标签之间?

<?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");
}
Run Code Online (Sandbox Code Playgroud)

Shi*_*ryu 7

文档(部分:如何访问HTML元素的属性?/提示):

// Append a element
$e->outertext = $e->outertext . '<div>foo<div>';
Run Code Online (Sandbox Code Playgroud)

您可以这样使用:

$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>
Run Code Online (Sandbox Code Playgroud)

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

$f = $html->find('head');
$e = $f->innertext;
Run Code Online (Sandbox Code Playgroud)

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