Clain Alexandru
Clain Alexandru

Reputation: 135

XML - merge multiple rows into one

I need some assistance with the following issue. I have an xml file with the following structure:

<attributes>
<record ProductId="103" Compatibility="iPhone"/>
<record ProductId="103" Color="Black"/>
<record ProductId="103" Material="Leather"/>
<record ProductId="103" Collection="iPhone"/>
</attributes>

The problem is that I want to generate only one record per ProductId because it makes it easier for me to handle the information. The record should look like:

<record ProductId="103" Compatibility="iPhone" Color="Black" Material="Leather" Collection="iPhone"/>

I believe that using xpath is the way to go, but I just can't get the synthax right. I'm using a php script to parse the xml file.

Any assistance will be greatly appreciated.

Upvotes: 1

Views: 90

Answers (1)

user1978142
user1978142

Reputation: 7948

Alternative you could just create a new one, but of course, get the necessary attributes first, gather them then apply them to the new one. Like this sample:

$xml_string = '<attributes><record ProductId="103" Compatibility="iPhone"/><record ProductId="103" Color="Black"/><record ProductId="103" Material="Leather"/><record ProductId="103" Collection="iPhone"/></attributes>';
$xml = simplexml_load_string($xml_string);
$record = new SimpleXMLElement('<attributes><record /></attributes>'); // create empty
$data = array();
foreach($xml->record as $entry) {
    $attributes = $entry->attributes(); // get attributes
    foreach($attributes as $key => $attribute) {
        $data[$key] = (string) $attribute; // put it inside a container temporarily
    }
}

// add the gathered attributes
foreach($data as $key => $value) {
    $record->record->addAttribute($key, $value);
}

echo $record->asXML();
// echo htmlentities($record->asXML());
// <?xml version="1.0"?> <attributes><record ProductId="103" Compatibility="iPhone" Color="Black" Material="Leather" Collection="iPhone"/></attributes>

Upvotes: 1

Related Questions