php:解析html:从body中提取脚本标签并在</ body>之前注入?

the*_*ss1 0 php dom html-content-extraction

我不关心库是什么,但我需要一种方法从页面的<.body.>中提取<.script.>元素(作为字符串).然后我想在<./ body.>之前插入提取的<.script.>.

理想情况下,我想将<.script.> s提取为2种类型;
1)外部(具有src属性的那些)2)嵌入式(代码在<.script.> <./ script.>之间)

到目前为止,我已经尝试过phpDOM,Simple HTML DOM和Ganon.
我对它们中的任何一个都没有运气(我可以找到链接并删除/打印它们 - 但每次都失败了脚本!).

替代
/sf/ask/1639042121/
(很抱歉重新发布,但已经过了24小时的尝试和失败,使用替代库,失败更多等).


基于来自@ alreadycoded.com的可爱的RegEx答案,我设法将以下内容整合在一起;

$output = "<html><head></head><body><!-- Your stuff --></body></html>"
$content = '';
$js = '';

// 1) Grab <body>
preg_match_all('#(<body[^>]*>.*?<\/body>)#ims', $output, $body);
$content = implode('',$body[0]);

// 2) Find <script>s in <body>
preg_match_all('#<script(.*?)<\/script>#is', $content, $matches);
foreach ($matches[0] as $value) {
    $js .= '<!-- Moved from [body] --> '.$value;
}

// 3) Remove <script>s from <body>
$content2 = preg_replace('#<script(.*?)<\/script>#is', '<!-- Moved to [/body] -->', $content); 

// 4) Add <script>s to bottom of <body>
$content2 = preg_replace('#<body(.*?)</body>#is', '<body$1'.$js.'</body>', $content2);

// 5) Replace <body> with new <body>
$output = str_replace($content, $content2, $output);
Run Code Online (Sandbox Code Playgroud)

这项工作做得多,而且不是那么慢(一秒钟的一小部分)

很遗憾没有任何DOM的东西正在工作(或者我没有通过naffed对象和操纵趟过).

Ran*_*gad 7

选择具有src-attribute的所有脚本节点

$xpathWithSrc = '//script[@src]';
Run Code Online (Sandbox Code Playgroud)

要选择包含内容的所有脚本节点:

$xpathWithBody = '//script[string-length(text()) > 1]';
Run Code Online (Sandbox Code Playgroud)

基本用法(用您的实际xpath查询替换查询):

$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DOMXpath($doc);

foreach($xpath->query('//body//script[string-length(text()) > 1]') as $queryResult) {
    // access the element here. Documentation:
    // http://www.php.net/manual/de/class.domelement.php
}
Run Code Online (Sandbox Code Playgroud)

  • 这只是phps默认的dom表示.它应该出现在几乎任何php5安装中(因为libxml在编译时以任何形式存在).处理格式错误的HTML是可能的,但这取决于.如果可能的话你应该避免它.或者事先对你的HTML进行sanatize. (2认同)

小智 5

$js = "";
$content = file_get_contents("http://website.com");
preg_match_all('#<script(.*?)</script>#is', $content, $matches);
foreach ($matches[0] as $value) {
    $js .= $value;
}
$content = preg_replace('#<script(.*?)</script>#is', '', $content); 
echo $content = preg_replace('#<body(.*?)</body>#is', '<body$1'.$js.'</body>', $content);
Run Code Online (Sandbox Code Playgroud)

  • 它很混乱,而且它用正则表达式解析 html(我们都知道这是禁忌)。 (2认同)