PHP DOMDocument 提取元素并创建新文档

HTML:


<head>

    <link rel="preload" href="/_next/list.js" as="script">

    <!-- ... other link elemens -->

    <style data-styled="" data-styled-version="4.2.0"></style>

</head>

任务:


从 head 中提取所有链接和样式标签,并使用主机路径更新 href 属性。

创建新的 html 字符串元素(一段 html),我们可以在我们的主 html 模板中输出它。

PHP:


$dom = new DOMDocument();

$dom->loadHTML($stringBody);

$xpath = new DOMXPath($dom);

$headItems = $xpath->query("//head/link[@rel='preload' or @rel='stylesheet'] | //head/style");


// now I want to create html string with updated attributes, but I'm lost here..

$head = new DOMDocument();

foreach ($headItems as $headNode) {

    $headNode->setAttribute('href', $host . $headNode->getAttribute('href'));

}

$links = $head->saveHTML($headNode);

echo $links; // echo html link tags


沧海一幻觉
浏览 215回答 1
1回答

拉丁的传说

试试这个:<?php$host = 'example.com';$stringBody = '<head>&nbsp; &nbsp; <link rel="preload" href="/_next/list.js" as="script">&nbsp; &nbsp; <!-- ... other link elemens -->&nbsp; &nbsp; <style data-styled="" data-styled-version="4.2.0"></style></head>';$dom = new DOMDocument();$dom->loadHTML($stringBody);$xpath = new DOMXPath($dom);$headItems = $xpath->query("//head/link[@rel='preload' or @rel='stylesheet'] | //head/style");$links = [];foreach ($headItems as $headNode) {&nbsp; &nbsp; if ($headNode->hasAttribute('href')) {&nbsp; &nbsp; &nbsp; &nbsp; $headNode->setAttribute('href', $host . $headNode->getAttribute('href'));&nbsp; &nbsp; }&nbsp; &nbsp; $links[] = $headNode->ownerDocument->saveHTML($headNode);}print_r($links);输出Array(&nbsp; &nbsp; [0] => <link rel="preload" href="example.com/_next/list.js" as="script">&nbsp; &nbsp; [1] => <style data-styled="" data-styled-version="4.2.0"></style>)
打开App,查看更多内容
随时随地看视频慕课网APP