Sundar
Sundar

Reputation: 159

how to convert xml as another xml using php

I want to convert one xml to another xml.for example if xml tag as string,

<book>
<title>test</test>
<isbn>1234567890</isbn>
<author>test</author>
<publisher>xyz publishing</publisher>
</book>

i want to convert above xml as,

<b00>
<t001>test</t001>
<a001>1234567890</a001>
<a002>test</a002>
<p001>xyz publishing </p001>
</b00>

how to convert xml using php

Upvotes: 1

Views: 438

Answers (1)

Gordon
Gordon

Reputation: 316969

You can use XSLT for the conversion.

PHP Code

$doc = new DOMDocument();
$doc->load('/path/to/your/stylesheet.xsl');
$xsl = new XSLTProcessor();
$xsl->importStyleSheet($doc);
$doc->load('/path/to/your/file.xml');
echo $xsl->transformToXML($doc);

XSLT File

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" />
    <xsl:template match="/">
        <b00><xsl:apply-templates/></b00>
    </xsl:template>
    <xsl:template match="title">
        <t001><xsl:value-of select="."/></t001>
    </xsl:template>
    <xsl:template match="isbn">
        <a001><xsl:value-of select="."/></a001>
    </xsl:template>
    <xsl:template match="author">
        <a002><xsl:value-of select="."/></a002>
    </xsl:template>
    <xsl:template match="publisher">
        <p001><xsl:value-of select="."/></p001>
    </xsl:template>    
</xsl:stylesheet>

Upvotes: 3

Related Questions