How to insert link tags between head tags on HTML using SimpleHtmlDom

﹥>﹥吖頭↗ 提交于 2020-01-13 05:19:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!