Search code examples
phpxmldatabaseloopssimplexml

Explode the attribute in XML File


I have an XML with attribute like this:

<products>
<product ProductName="One" ProductCategory="Software::Utilities::Email">
<product ProductName="Two" ProductCategory="Software::Video::Editing">
<product ProductName="Three" ProductCategory="Software::Audio::Converter">
</products>

And how can I explode the "ProductCategory" attribute and separated it like this:

<products>
<product ProductName="One" ProductCategory="Software">
<product ProductName="One" ProductCategory="Utilities">
<product ProductName="One" ProductCategory="Email">
<product ProductName="Two" ProductCategory="Software">
<product ProductName="Two" ProductCategory="Video">
<product ProductName="Two" ProductCategory="Editing">
<product ProductName="Three" ProductCategory="Software">
<product ProductName="Three" ProductCategory="Audio">
<product ProductName="Three" ProductCategory="Converter">
</products>

Solution

  • An Example for you

    <?php
    $string = <<<XML
    <products>
        <product ProductName="One" ProductCategory="Software::Utilities::Email"></product>
        <product ProductName="Two" ProductCategory="Software::Video::Editing"></product>
        <product ProductName="Three" ProductCategory="Software::Audio::Converter"></product>
    </products>
    XML;
    
    $xml = simplexml_load_string($string);
    $obj = json_decode(json_encode($xml), true);
    
    $new_xml = '<products>';
    
    foreach($obj['product'] as $val){
        $name = $val['@attributes']['ProductName'];
        $pro = explode('::', $val['@attributes']['ProductCategory']);
        foreach($pro as $k=>$v){
            $new_xml .= '<product ProductName="'.$name.'" ProductCategory="'.$v.'"></product>';
        }
    }
    $new_xml .= '</products>';
    $file = fopen("test.xml","w");
    fwrite($file, $new_xml);
    fclose($file);
    ?>