FarbodKain FarbodKain - 7 months ago 9
PHP Question

create xml from other xml files by php

i have 2 xml files look likes below:

<root>
<Item0>
<hotel_name>hotel X</hotel_name>
<hotel_details>
<Item0>
<title>Room X</title>
<PriceA>300$</PriceA>
</Item0>
<Item1>
<title>Room Y</title>
<PriceA> 400$</PriceA>
</Item1>
</hotel_details>
</Item0>




i want to combine these files to look like these:

<root>
<xml file 1>
<item name="Hotel X">
<details>
<item name="Room X" price="300$" />
<item name="Room Y" price="400$" />
</details>
</item>
</xml file 1>




any advice really appreciated.

Answer

The easiest way for beginner would be to read the file one by one and evaluate every lines with that function strpos:

http://php.net/manual/fr/function.strpos.php

Another way is to use regular expressions like this:

$destination = preg_replace(
     array(
        '/<Item\d+>\s+<title>(.*?)<\/title>\s+<PriceA>(.*?)<\/PriceA>\s+<\/Item\d+>/i',
        '/<Item(\d)>\s+<hotel_name>(.*?)<\/hotel_name>(\s+)<hotel_details>([\S\s]+?)<\/hotel_details>(\s+)<\/Item\1>/i'
     ),
     array(
        '<item name="$1" price="$2" />',
        "<xml file $1>\n<item name=\"$2\">$3\t<details>$4</details>$5</item>\n</xml file $1>"
    ),
    $source
);

I think with that I manage to preserve pretty much the initial idea (regarding your short example).

enter image description here

Here's my whole coding I used for test :

http://sandbox.onlinephpfunctions.com/code/79891956977d3f2faa2cb6a8a8044f7bf494e9a3

If you have question, write a comment and I will answer you tomorrow. If everything works pretty much as you wanted, then accept my answer.

Comments