解析XML文件时preg_replace存在问题。
<?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>
这是PHP脚本,它打开一个文件,更改特殊字符,在文件中搜索匹配项,然后用指定的字符串替换它们:
<?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);
?>
主要问题是它返回一个空页面。 显然preg_replace会返回错误,因此它的输出为空。
我知道我应该使用像SimpleXML这样的XML解析器来实现这个目的,但是我没有足够的能力来写这样的东西。
我将非常感谢您提供的任何帮助。