簡體   English   中英

使用 PHP 將 HTML 代碼添加到現有 HTML 文件

[英]Add HTML Code to existing HTML file using PHP

在我的 index.html 中有幾個鏈接,看起來像這樣

 <div id="links">
    <a class="link" href="download1.html" target="_blank">Download 1</a>
    <a class="link" href="download2.html" target="_blank">Download 2</a>
    <a class="link" href="download3.html" target="_blank">Download 3</a>
    <a class="link" href="download4.html" target="_blank">Download 4</a>
</div>

我想要做的是,通過 PHP 向這個 div 添加新的鏈接。 我用 DOM 和 appendChild 嘗試了一些東西,但它沒有像我想要的那樣工作。

<?php
$filename = $_GET['filename'];
$tabtitle = $_GET['tabtitle'];

$dom = new DOMDocument;
$dom = loadHTMLFile('index.html');

$node = "<a class="link" href="{$filename}.html" target="_blank">{$tabtitle}</a>";
$findelement = $dom->getElementById('links');
$dom->parentNode->appendChild($findelement, $node);

echo $dom->saveXML();?>

我已經能夠通過 PHP 創建引用 HTML 文件,但我不想一直手動添加這些鏈接。

謝謝你的幫助!

正如評論中提到的,有一些小錯誤,當如下更正時,應該會產生我認為你正在嘗試做的事情:

<?php

    if( isset(
        $_GET['filename'],
        $_GET['tabtitle']
    )){
        $filename = $_GET['filename'];
        $tabtitle = $_GET['tabtitle'];
        
        
        $dom = new DOMDocument;
        $dom->loadHTMLFile( __DIR__ . '/index.html' );
        
        
        $div=$dom->getElementById('links');
        
        $a=$dom->createElement('a',$tabtitle);
        $a->setAttribute('class','link');
        $a->setAttribute('href',$filename.'.html');
        $a->setAttribute('target','_blank');
        
        $div->appendChild($a);
        
        echo $dom->saveHTML();
    }
?>

示例輸出

保存index.html文件(對我來說稱為x-index.html以避免與現有文件沖突)

<?php
    
    if( isset(
        $_GET['filename'],
        $_GET['tabtitle']
    )){
        $filename = $_GET['filename'];
        $tabtitle = $_GET['tabtitle'];
        
        
        $dom = new DOMDocument;
        $dom->loadHTMLFile( __DIR__ . '/x-index.html' );
        
        
        $div=$dom->getElementById('links');
        
        $a=$dom->createElement('a',$tabtitle);
        $a->setAttribute('class','link');
        $a->setAttribute('href',$filename.'.html');
        $a->setAttribute('target','_blank');
        
        $div->appendChild($a);
        
        echo $dom->saveHTML(); //display
        
        
        $dom->saveHTMLFile( __DIR__ . '/x-index.html' ); //save
    }
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM