When developing with PHP, you may encounter the warning "Warning: Cannot modify header information...". This typically happens because HTTP headers have already been sent to the browser, and any further modification fails. One common HTTP header to set is the encoding, known as PHP header encoding.
Using PHP’s built-in header function, you can send raw HTTP header information to specify the character encoding of the page. For example:
header("Content-Type:text/html;charset=utf-8");
Another way is to configure the default charset in the PHP configuration file php.ini. This ensures the charset is applied automatically during script execution. For example:
default_charset = "utf-8"
<?php // Set UTF-8 encoding header("Content-Type:text/html;charset=utf-8"); echo "<html><head><title>Page Title</title></head><body><p>This is a UTF-8 page!</p></body></html>"; ?>
This code outputs an HTML page with UTF-8 encoding. Even if the page contains Chinese characters, no garbled text will appear. The key is setting the content type and charset via the header function.
<?php // Set GB2312 encoding header("Content-Type:text/html;charset=gb2312"); echo "<html><head><title>Page Title</title></head><body><p>This is a GB2312 page!</p></body></html>"; ?>
This example sets the header encoding to GB2312, which is suitable for compatibility with older Simplified Chinese encodings.
This article introduced the basic concept of PHP header encoding and two common ways to set it: using the header function and modifying the php.ini configuration file. It also showed examples of how to output pages with different encodings to help developers effectively avoid encoding issues and improve webpage compatibility and user experience.