XML Split Node on . value

user3754085

I've used SO for many years and always found an answer but this time I have got myself well and truly lost.

I have an xml file I would like to split the compatbility into well formed xml

`<product>
<item>
<partno>abc123</partno>
<Compatbility>model1: 110C, 115C, 117C. model2: 1835C, 1840C. model3: 210C, 215C, 3240C.</Compatbility>
</item>
</product>`

In Compatbility the word model changes with each item entry although the : after model is always there as is the . after each model group.

Should I use SimpleXml DomXml or an xpath to get the following result

`<product>
<item>
<partno>abc123</partno>
<Compatbility>
<model>model1: 110C, 115C, 117C.</model>
<model>model2: 1835C, 1840C.</model> 
<model>model3: 210C, 215C, 3240C.</model>
</Compatbility>
</item>
</product>`

Thanks

user1978142

First ofcourse, you need to convert that first into something that you can manipulate (arrays). Then the usual parsing (using explode). In the end, you will need to create a new xml again. Consider this example:

$xml_string = '<product><item><partno>abc123</partno><Compatbility>model1: 110C, 115C, 117C. model2: 1835C, 1840C. model3: 210C, 215C, 3240C.</Compatbility></item></product>';
$original_xml = simplexml_load_string($xml_string);
$data = json_decode(json_encode($original_xml), true);
$compatbility = $data['item']['Compatbility']; // get all compatibility values
// explode values
$compatbility = array_filter(array_map('trim', explode('.', $compatbility)));

$new_xml = new SimpleXMLElement('<product/>'); // initialize new xml
// add necessary values
$new_xml->addChild('item')->addChild('partno', $data['item']['partno']);
$new_xml->item->addChild('Compatbility');
// loop the values and add them as children
foreach($compatbility as $value) {
    $value = trim(preg_replace('/(\w+):/', '', $value));
    $new_xml->item->Compatbility->addChild('model', $value);
}
echo $new_xml->asXML(); // output as xml

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related