1

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

5
  • ya its possible in str_replace. Is there is any another way to convert it.I am using onix xml format for book upload process. In onix xml they use two types of xml tags for example <ISBN> similar tag they use <b004>. Like that there are several tags. Commented Oct 10, 2012 at 12:51
  • 1
    Google for XSLT and then see how far you can get with it. But first, fix your invalid XML. Commented Oct 10, 2012 at 12:56
  • thank you Gordon, i will use XSLT for conversion. Commented Oct 10, 2012 at 13:06
  • 1
    off topic: why would anyone design an XML schema that looked like the second code block? I presume this is an existing schema that you've been asked to map to, but honestly, that is a monstrosity. XML is not the neatest or most efficient of formats, but one of the key reasons for using it is because it XML allows you to give your data sensible field names. If you're going to name them t001 and a002, it kinda defeats the point. You may as well have have used a flat CSV file. Commented Oct 10, 2012 at 13:24
  • can you please review the answers you have been given and either accept the one that helped you most/solved your problem or point out why none of the answers solved your problem. thanks Commented Oct 26, 2012 at 11:34

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.