scraly
scraly

Reputation: 119

PHP xml - concatenate severals files in one

I have 4 xml files and I want to create one unique file with the content of each files except the 2 first lines and the last line.

Details:

my xml files:

 <?xml version="1.0"?>
 <Clients xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <Client>
    <client_id>123458</client_id>
    <client_type>People</client_type>
    <client_sub_type>Sub people</client_sub_type>
    <name>Alerich</name>
    <surname>Higor</surname>
 </Client>
 <Client>
    <client_id>5487</client_id>
    <client_type>People</client_type>
    <client_sub_type>Sub people</client_sub_type>
    <name>Newman</name>
    <surname>Matew</surname>
 </Client>
 </Clients>

1.xml, 2.xml, 3.xml and 4.xml have a content like this.

And i want to create a final.xml file which start with

 <?xml version="1.0"?>
 <Clients xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

end with:

 </Clients>

and between theses lines i want all lines for fourth files.

Have you some tips?

Thanks.

Upvotes: 0

Views: 1259

Answers (2)

chiborg
chiborg

Reputation: 28124

You can use the PHP DOM function to achieve this:

$d1 = new DOMDocument();
$d1->load('1.xml');
$root = $d1->getElementsByTagName('Clients')->item(0);

// List of other xml files
$files = array('2.xml', '3.xml', '4.xml');

foreach($files as $file) {
    $d2 = new DOMDocument();
    $d2->load($file);
    foreach($d2->getElementsByTagName('Client') as $elem) {
        $newNode = $d1->importNode($elem, true);
        $root->appendChild($newNode);
    }
}
$d1->saveXMLFile('newfile.xml'));

A general tip: Don't make any assumptions on line breaks in XML files! So your premise of "first two lines and last line of the file" may be wrong. Using XML functions instead of string functions avoids these problems.

Upvotes: 3

Christoph Winkler
Christoph Winkler

Reputation: 6418

Read the files with fgets and check for the xml or clients tag with preg_match. If the line doesn't match, write the line to the new file. Of course you have to place a new xml and clients tag around the new file.

Upvotes: 0

Related Questions