Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xml insertion at specific point of xml file

I want to insert the following line into my xml file:

<?xml-stylesheet type="text/xsl" href="http://example.com/livesearch.xsl"?>

immediately after:

<?xml version="1.0" encoding="UTF-8" ?>

in my xml file.

Currently I use this (awful) method:

$G['xml'] = str_replace('<?xml version="1.0" encoding="UTF-8" ?>', '<?xml version="1.0" encoding="UTF-8" ?><?xml-stylesheet type="text/xsl" href="http://example.com/livesearch.xsl"?>', $G['xml']);

What is the correct way to do this with DomDocument in php?

Thanks

like image 921
khany Avatar asked Dec 06 '25 01:12

khany


1 Answers

The line you want to insert is called a processing instruction. You can add it with DOM like this:

$dom = new DOMDocument();
$dom->loadXml('<?xml version="1.0" encoding="UTF-8" ?><root/>');

$dom->insertBefore(
    $dom->createProcessingInstruction(
        'xml-stylesheet',
        'type="text/xsl" href="http://example.com/livesearch.xsl"'
    ),
    $dom->documentElement
);
echo $dom->saveXml();

Output:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="http://example.com/livesearch.xsl"?>
<root/>

On a sidenote, it might feel wrong to use str_replace but if it works … it works.

like image 64
Gordon Avatar answered Dec 07 '25 17:12

Gordon