1

私はphpが初めてです。このようなテキストを含むテキストファイルがあります

<??blah blahh blah
   blah blah blah
   .......
??>

<??blah blahh blah
   blah blah blah
   .......
??>

<??blah blahh blah
   blah blah blah
   ...... .
??>

これは、メイン データが中間<?? and ??>にあることを意味します。配列内のすべてのメイン データを含む配列を作成したい (これらの文字を削除する<?? & ??>)。MySql テーブルにデータ項目を挿入できるようにします。このファイルから配列を作成する方法がわかりません。

手伝ってくれてありがとう!!!

4

4 に答える 4

4

うまくいけば、これは助けになるでしょう。

まず、PHP に関連付けられているファイル ライブラリを調べる必要があります。

参考http ://www.php.net/manual/en/ref.filesystem.php

fopen と fread を使用すると、問題のファイルを開き、そこから解析できます。

<?php
// get contents of a file into a string
$filename = "something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

次に、簡単な文字列操作を使用して、重要な情報を取得します。を使用splitすると、ファイルの内容を適切なものに切り分けることができます。

参考: http: //php.net/manual/en/function.split.php

<?php
// sanitize content headers
$contents = split("<\?\?", $contents);
foreach($contents as $content) {
   // remove content footers
   str_replace("??>", "", $content);
}
?>

最後に、split を使用して作成したばかりの配列内のすべての要素を調べ、それらをデータベースに挿入します。

参考: http: //php.net/manual/en/book.mysql.php

<?php
// sanitize content headers
$contents = split("<\?\?", $contents);
foreach($contents as $content) {
   if (empty($content)) {
       continue;
   }
   // remove content footers
   str_replace("??>", "", $content);

   // insert into database
   mysql_query("INSERT INTO `something` VALUES ('" . $content . "')");
}
?>

全体として、最終的なコードは次のようになります。

<?php
// get contents of a file into a string
$filename = "something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

// sanitize content headers
$contents = split("<\?\?", $contents);
foreach($contents as $content) {
   if (empty($content)) {
       continue;
   }
   // remove content footers
   str_replace("??>", "", $content);

   // insert into database
   mysql_query("INSERT INTO `something` VALUES ('" . $content . "')");
}
?>

幸運を!

于 2012-07-06T17:37:22.460 に答える
3

次のように、爆発と少しの創造性でこれを行うことができるはずです。

$str = file_get_contents( 'yourfile.txt');
$array = explode( '<??', $str);
array_shift( $array); // first element is empty
array_walk( $array, function( &$el) { $el = str_replace( '??>', '', $el); });
var_dump( $array);

これで、配列は次のようになります。

array(3) {
  [0]=>
  string(52) "blah blahh blah
   blah blah blah
   .......


"
  [1]=>
  string(52) "blah blahh blah
   blah blah blah
   .......


"
  [2]=>
  string(49) "blah blahh blah
   blah blah blah
   ...... .
"
}
于 2012-07-06T17:40:58.310 に答える
2
<?php    
preg_match_all("/(?:<\?\?)(.+?)(?:\?\?>)/sm",file_get_contents("test.txt"),$result);
print_r($result[1]);
?>
于 2012-07-06T18:02:29.493 に答える
1

試す:

<?php

$filestring = file_get_contents('YOUR_FILE_TO_PARSE');
$pattern = '/<\?\?[\w\s.]*\?\?>/';
preg_match($pattern, $filestring, $matches);

?>

ここで、$matchesは配列になります

于 2012-07-06T17:51:16.107 に答える