How do I add <?xml-stylesheet...?> to the DOMDocument?

Asked 1 years ago, Updated 1 years ago, 125 views

<?php class SitemapGenerator{
    private$sitemap;
    private$urlset=array();

    function__construct(){
        $this->sitemap=new DOMDocument('1.0', 'UTF-8');
        $this->sitemap->preserveWhiteSpace=false;
        $this->sitemap->formatOutput=true;

        $this->urlset=$this->sitemap->appendChild($this->sitemap->createElement("urlset"));
        $this->urlset->setAttribute('xmlns','http://www.sitemaps.org/schemas/sitemap/0.9');
    }

    function add($params){
        $url = $this->urlset->appendChild($this->siteemap->createElement('url'));
        foreach($params as$key=>$value){
            if(strlen($value)){
                $url->appendChild($this->siteemap->createElement($key,$value));
            }
        }
    }

    function generate($file=null){
        if(is_null($file){
            header("Content-Type:text/xml; charset=utf-8";
            echo$this->sitemap->saveXML();
        } else{
            $this->sitemap->save($file);
        }
    }
}

Regarding the above code, the first part of the xml is
From <?xml version="1.0" encoding="UTF-8"?> only,
<?xml version="1.0" encoding="UTF-8"?>?xml-stylesheet type='text/xsl'href='xsl-stylesheet2.xsl'?>.

How should I make the corrections?

Please let me know if you know more.Thank you for your cooperation.

php dom

2022-09-30 17:51

1 Answers

In an xml document, syntax beginning with <? and ending with ? is called Processing Instruction.

The style sheet description in this question corresponds to this processing instruction.
The DOMDocument class has a method createProcessingInstruction to write this processing instruction syntax in advance, so I think it can be achieved using this method.

function generate($file=null){
    if(is_null($file){
        header("Content-Type:text/xml; charset=utf-8";

        /* Generating Processing Instruction Syntax*/
        $insertBefore=$this->sitemap->firstChild;//Get the part to insert
        $styleSheetXml=$this->sitemap->createProcessingInstruction('xml-stylesheet', "type='text/xsl'href='xsl-stylesheet2.xsl');// Stylesheet processing instruction generation
        $this->sitemap->insertBefore($styleSheetXml, $insertBefore);//Insert to specified location

        echo$this->sitemap->saveXML();
    } else{
        $this->sitemap->save($file);
    }
}


2022-09-30 17:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.