How to Change a Font Type With PHP


Fonts on websites, like all other text characteristics, are manipulated using HTML. The font type, as well as its font family, color and size, are standard aspects that are changed often. Sometimes, it is necessary to dynamically change one of these font types using conditions from other data sources. For example, the font for an input form field on a web page may need to be bold and red to show the user they forgot to input required data. While HTML displays the font, PHP can be used to alter the HTML font statement that renders the final text output.

Things You'll Need

  • PHP Compiler
  • Confirm with your Web hosting provider that your account has PHP privileges. You cannot use PHP to change a font type without access to the PHP compiler. The PHP code in the document will be ignored by the Web server and appear as foreign symbols on the Web page.

  • Create the font declaration using standard HTML. This involves the "<font>" tag and any parameters you desire to configure the font type. For example, "<font color='cyan' size=4>" sets the font color to cyan and its size to 4.

  • Call the PHP compiler by surrounding the font declaration with PHP tags. On a line above the font statement, type "<?php\" to open the PHP compiler. Type "?>" on a line beneath the font statement to turn the compiler off. The HTML statement now exists within the PHP section of the code, but is not formatted for the compiler to understand.

  • Enclose the HTML font declaration inside the "echo" PHP function. Anything output to a Web browser from within PHP code is displayed using screen printing functions liked "echo". Before the font statement, type "echo" followed by the entire HTML font statement in double quotes.

  • Type a semicolon at the end of the "echo" statement to complete the statement.

    The final output reads:

    echo "<font color='cyan' size=4>PHP is controlling the font of this sentence</font>";

  • Add additional HTML content to the document if desired. The PHP is processed only in the small section where the font is declared. All data outside the "<?php" and "?>" tags is ignored by the server and sent directly to the Web browser, as usual.

Tips & Warnings

  • Note the use of single quotes within the font attributes. HTML usually uses double quotes, however, it also understands single quotes or the full omissions of quotes for single-word attributes. When enclosing an HTML statement in PHP to control its output in this way, double quotes should be avoided or PHP may interpret them as the end of the "echo" statement, which uses its own double quotes.
  • Don't type the outer quotes when implementing the code.

Related Searches


  • Photo Credit Ciaran Griffin/Lifesize/Getty Images
Promoted By Zergnet


You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!