简体   繁体   中英

Add HTML Code to existing HTML file using PHP

In my index.html there are several Links and it looks like this

 <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>

and what I want to do is, adding new Links to this div via PHP. I tried something with DOM and appendChild but it isn't working like I want.

<?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();?>

I'm already able to create the refering HTML File via PHP but I don't want to add these Links above manually all the time.

Thanks for your help!

As mentioned in the comments there are a few minor errors which, when corrected as below, should yield what I think you are trying to do:

<?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();
    }
?>

示例输出

To save the index.html file ( for me called x-index.html to avoid conflict with existing file )

<?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
    }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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