2016-11-22 5 views
1

タイトルは自明です。php foreach preg_match'd行、次の行を取得

xmlファイルを1行ずつループし、特定の行(その行の属性を取得)と一致させ、その行の次の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

こんにちはKris、このコードには欠けている変数がたくさんあります。 XLinesと$ arrayはどこから来たのですか?と$ X? –

+0

このコードはあなたのforeach clouseを置き換え、$ Xを定義する必要があります。 。 –

+0

$ XLinesは定義されておらず、$ arrayもありません –