There is a problem with preg_replace while parsing an XML file.
<?xml version="1.0" encoding="UTF-8"?>
<Products>
<Product>
<!--- .. -->
<Properties>
<!--- .. -->
<Property>
<Id>bdfe66a6-707f-11e4-bac6-50b7c36a6683</Id>
<Title>m3</Title>
<Value>2,25</Value>
</Property>
</Properties>
<!---..-->
<Packages>
<Package>
<Id>bdfe66a6-707f-11e4-bac6-50b7c36a6683</Id>
<Title>m3</Title>
<Value>2,25</Value>
</Package>
</Packages>
</Product>
</Products>
Here is PHP script, which opens a file, changes special characters, searches the file for matches and then replaces them with specified strings:
<?php
//Replacing symbols < > with < and >
$xml_origin = str_replace("<","<",str_replace(">",">",file_get_contents("import.xml")));
//Searching for all matches
preg_match_all("/((\<)Packages>\s*
(\<)Id>\s*.*?(\<)\/Id>\s*
(\<)Title>\s*.*?(\<)\/Title>\s*
(\<)Value>.*?(\<)\/Value>\s*)/",
$xml_origin, $matches, PREG_PATTERN_ORDER);
//Making an array: key - ID, value - Title
foreach ($matches[0] as $key => $val) {
preg_match("/(\<)Id(\>)\s*.*?(\<)\/Id(\>)\s*/",
$val, $ids);
$proc_ids[] = $ids[0];
preg_match("/(\<)Title(\>)\s*.*?(\<)\/Title(\>)/",
$val, $titles);
$proc_titles[] = $titles[0];
}
$data = array_combine($proc_ids, $proc_titles);
//Making an array with replacing strings
foreach ($data as $id => $title) {
$search_line[] = "/((\<)Property(\>)\s*".trim($id)."\s*".trim($title).")/";
if ($title == "<Title>m3</Title>"){
$match_line[] = "<Property> <Id>some_id1</Id> ".trim($title);
}
elseif ($title == "<Title>m2</Title>") {
$match_line[] = "<Property> <Id>some_id2</Id> ".trim($title);
}
elseif ($title == "<Title>un</Title>") {
$match_line[] = "<Property> <Id>some_id3</Id> ".trim($title);
}
}
//Replacing strings
$xml_processed = preg_replace($search_line,$match_line, $xml_origin);
print_r($xml_processed);
?>
The main problem is that it returns an empty page. Apparently preg_replace returns an error, so it's output is empty.
I know that I should use XML parsers like SimpleXML for this purpose, but I didn't get it enough to write something like that.
I will be grateful for any help you can provide.