我希望标题是自解释的。PHP foreach preg_match'd行,得到下一行
我想循环一个xml文件一行一行,然后匹配一个特定的行(从该行获取属性),然后获取该行后面的下一个X行。
我有下面的代码,它试图做到这一点,但我似乎无法弄清楚如何得到后面的X行。
$file = 'Electric.xml';
$lines = file($file);//file in to an array
foreach($lines as $line){
$reads = element_attributes('WINDOW',$line);
if($reads['class'] == 'Bracelets'){
print_r($reads);
}
if($reads['class'] == 'Handbags'){
print_r($reads);
}
}
function element_attributes($element_name, $xml) {
if ($xml == false) {
return false;
}
// Grab the string of attributes inside an element tag.
$found = preg_match('#<'.$element_name.
'\s+([^>]+(?:"|\'))\s?/?>#',
$xml, $matches);
if ($found == 1) {
$attribute_array = array();
$attribute_string = $matches[1];
// Match attribute-name attribute-value pairs.
$found = preg_match_all(
'#([^\s=]+)\s*=\s*(\'[^<\']*\'|"[^<"]*")#',
$attribute_string, $matches, PREG_SET_ORDER);
if ($found != 0) {
// Create an associative array that matches attribute
// names to attribute values.
foreach ($matches as $attribute) {
$attribute_array[$attribute[1]] =
substr($attribute[2], 1, -1);
}
return $attribute_array;
}
}
// Attributes either weren't found, or couldn't be extracted
// by the regular expression.
return false;
}
不能使用XML解析器我害怕。这是不正确的XML。 –
@Ke。它是如此糟糕,即使DOMdocument失败..? :O在这种情况下,我感觉到你,祝你好运! – ChristianF
是的,那很糟!我没有创建该文件。我没有选择,我需要数据! –