简体   繁体   English

使用 PHP HTML Parser 将 HTML 附加到标签

[英]Append HTML to a tag using PHP HTML Parser

I am working on a project in which I will need to use PHP to modify the contents of any given website.我正在开发一个项目,在该项目中我需要使用 PHP 来修改任何给定网站的内容。 To do this I am using this PHP HTML Parser .为此,我使用了这个PHP HTML Parser

Now, I need to be able to add a <style> tag to the end of the <head> of a document that's been loaded to $html using $html->loadFromFile($url) but I cannot seem to find an append() method in any of the classes.现在,我需要能够将<style>标记添加到使用$html->loadFromFile($url)加载到$html的文档的<head>末尾,但我似乎找不到append()任何类中的方法。 Is there any way for me to achieve this?我有什么办法可以实现这一目标吗?

Here is my code这是我的代码

require("vendor/autoload.php");
use PHPHtmlParser\Dom;
$html = new Dom;

$url = "https://www.example.com";
$html->loadFromFile($url);

// I need to do this:
$css = "<style>#custom{css:code;}.goes{over:here;}</style>"
$html->find("head")->append($css);

You can find the instruction for appending an element in the documentation under "How to access the HTML element's attributes?"->"Tips".您可以在“如何访问 HTML 元素的属性?”->“提示”下的文档中找到附加元素的说明 In this case it would be:在这种情况下,它将是:

$head = $html->find("head")[0];
$head->outertext = $head->outertext . $css;

I think you can use it我认为你可以使用它

$head = $html->getElementsByTagName('head');
$head->appendChild($css);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM