まったくループしないでください。これはどうですか (ファイルごとに 1 つのレコードを想定)。
$inrec = file_get_contents('input');
$inrec = str_replace( "\n'", "'", str_replace( array( 'HD ', 'BY ', 'PD ', 'LP', 'TD' ), array( "'HD' => '", "','BY' => '", "','PD' => '", "','LP' => '", "','TD' => '" ), str_replace( "'", "\\'", $inrec ) ) )."'";
eval( '$record = array('.$inrec.');' );
var_export($record);
結果:
array (
'HD' => 'Alcoa Earnings Soar; Outlook Stays Upbeat ',
'BY' => 'By James R. Hagerty and Matthew Day ',
'PD' => '12 July 2011',
'LP' => '
Alcoa Inc.\'s profit more than doubled in the second quarter.
The giant aluminum producer managed to meet analysts\' forecasts.
However, profits wereless than expected
',
'TD' => '
Licence this article via our website:
http://example.com',
)
ファイルごとに複数のレコードが存在する可能性がある場合は、次のようなことを試してください。
$inrecs = explode( 'HD ', file_get_contents('input') );
$records = array();
foreach ( $inrecs as $inrec ) {
$inrec = str_replace( "\n'", "'", str_replace( array( 'HD ', 'BY ', 'PD ', 'LP', 'TD' ), array( "'HD' => '", "','BY' => '", "','PD' => '", "','LP' => '", "','TD' => '" ), str_replace( "'", "\\'", 'HD ' . $inrec ) ) )."'";
eval( '$records[] = array('.$inrec.');' );
}
var_export($records);
編集
これは $inrec 関数が分割されたバージョンで、より簡単に理解できるようになっています。さらに、いくつかの調整が加えられています: 改行を削除し、先頭と末尾のスペースを削除し、データが信頼できないものからのものである場合に EVAL でバックスラッシュの問題に対処します。ソース。
$inrec = file_get_contents('input');
$inrec = str_replace( '\\', '\\\\', $inrec ); // Preceed all backslashes with backslashes
$inrec = str_replace( "'", "\\'", $inrec ); // Precede all single quotes with backslashes
$inrec = str_replace( PHP_EOL, " ", $inrec ); // Replace all new lines with spaces
$inrec = str_replace( array( 'HD ', 'BY ', 'PD ', 'LP ', 'TD ' ), array( "'HD' => trim('", "'),'BY' => trim('", "'),'PD' => trim('", "'),'LP' => trim('", "'),'TD' => trim('" ), $inrec )."')";
eval( '$record = array('.$inrec.');' );
var_export($record);
結果:
array (
'HD' => 'Alcoa Earnings Soar; Outlook Stays Upbeat',
'BY' => 'By James R. Hagerty and Matthew Day',
'PD' => '12 July 2011',
'LP' => 'Alcoa Inc.\'s profit more than doubled in the second quarter. The giant aluminum producer managed to meet analysts\' forecasts. However, profits wereless than expected',
'TD' => 'Licence this article via our website: http://example.com',
)