2016-11-22 86 views
1

我希望标题是自解释的。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; 
} 

回答

0

使用合适的解析器like SimpleXML来解析文件。那么你的问题就变得微不足道了。 PHP manual contains a tutorial可帮助您开始使用。

在这种情况下,您只需循环查看要查找的标记的属性,直到找到匹配项。然后,循环下一个#元素,将它们保存到数组中。
事情是这样的:

$xml = new SimpleXML ("file.xml"); 
foreach ($xml->node->element as $element) { 
    if ($element->attribute != "match") { 
     continue; 
    } 

    // If we get here we want to save the next # lines/elements. 
} 
+0

不能使用XML解析器我害怕。这是不正确的XML。 –

+0

@Ke。它是如此糟糕,即使DOMdocument失败..? :O在这种情况下,我感觉到你,祝你好运! – ChristianF

+0

是的,那很糟!我没有创建该文件。我没有选择,我需要数据! –

0
$linesLength = count($lines); 
$XLines = array(); 
for($index = 0; $index < $linesLength; $index++){ 

    $reads = element_attributes('WINDOW',$line); 

    if($reads['class'] == 'Bracelets'){ 
     print_r($reads); 
     $XLines[] = array_slice($array, $index, $X); 
     $index += $X; 
    } 

    if($reads['class'] == 'Handbags'){ 
     print_r($reads); 
     $XLines[] = array_slice($array, $index, $X); 
     $index += $X; 
    } 
} 
+0

嗨克里斯,这个代码中有很多缺少的变量。 XLines和$ array从哪里来?和$ X? –

+0

这段代码只是替换你的foreach clouse,而你必须定义$ X。 。 –

+0

$ XLines没有定义,也不是$ array –