File UTF8 ohne BOM

Thomasio

Erfahrenes Mitglied
Wenn ich eine neue Datei anlege, etwa so:

Code:
$MyFile = fopen("../ordner/datei.txt", "w");
fwrite($MyFile, "Irgendwas");
fclose($MyFile);

Wie stelle ich es an, dass die Datei im Format UTF8 ohne BOM angelegt wird, für den Fall, dass "Irgendwas" diverse Sonderzeichen enthält?
 
utf8_encode() ist Unsinn, weil das Script selbst in UTF8 geschrieben ist und somit "Irgendwas" sowieso schon UTF8 encoded ist.
Ob in dem Fall PHP automatisch eine UTF8-Datei anlegt ist genau meine Frage und zusätzlich müsste ich wissen, ob die dann mit oder ohne BOM ist.
 
Der kommt echt tatsächlich aus einer anderen Quelle, um nicht zu sagen MySql, ist aber auch da UTF8_general_ci und wird auch als UTF8 gelesen.
 
Die Datei dürfte dann in UTF-8 sein, aber ohne BOM. Den BOM muss man eigentlich immer selbst reinschreiben (IMHO).

Warum probierst du es nicht selbst? Notepad++ zeigt alle Informationen zum Encoding an. Aber ich will mal nicht so sein ;-)

PHP:
<?php
/******************************
 * -- --------------------------------------------------------

--
-- Tabellenstruktur für Tabelle `b`
--

CREATE TABLE IF NOT EXISTS `b` (
  `a` int(11) NOT NULL AUTO_INCREMENT,
  `t` varchar(100) NOT NULL,
  PRIMARY KEY (`a`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

--
-- Daten für Tabelle `b`
--

INSERT INTO `b` (`a`, `t`) VALUES
(1, 'äüöß');
 */
error_reporting(E_ALL|E_STRICT);
ini_set('display_errors', 1);

class BTable
{
	private $a;
	private $t;
	
	public function getA()
	{
		return $this->a;
	}
	
	public function getT()
	{
		return $this->t;
	}
}

try
{
	$db = new PDO('mysql:dbname=test;host=127.0.0.1', 'test', '',
			array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'", 
					  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
			);
	
	$statement = $db->prepare('SELECT `t` FROM `b`');
	if(!$statement->execute())
	{
		throw new Exception("Executing statement failed!");
	}
	
	$result = $statement->fetchObject('BTable');
	assert( $result instanceof BTable );
	
	$fp = fopen( dirname(__FILE__) . '/encoding.txt', 'w');
	if($fp)
	{
		fprintf($fp, "%s\n", $result->getT());
		fclose($fp);
	}
	else
	{
		throw new Exception("Could not open file!");
	}
	echo "Success!";
}
catch(Exception $exception)
{
	echo $exception->getMessage();
}

Gespeichert als UTF-8-PHP-Script.

Im Anhang siehst du das Ergebnis.
 

Anhänge

  • encoding.png
    encoding.png
    34 KB · Aufrufe: 19

Neue Beiträge

Zurück