PHP

Convert plain HTML to XHTML

CK CK 3788 
Created at
Updated at  
453 0 0

Below is the example of converting from plain HTML to XHTML.

<?php 
/** 
  * Take a look at the Remark-Lines of the function-header 
  *  
  * function autoAdjustToXHMTL($string) 
  *  
  * Tries to make out of the given string a xhtml-compatible string, 
  * that means that the return-string could be wrapped within a xml. 
  * 
  * Example: $string = "<big><I>something<br></big> blabla" 
  *          return = "<big><i>something><br /></i></big> blabla" 
  * 
  * As you can see, the folowing will be changed: 
  *  - converted "<I>" to "<i>", as all html-nodes will be converted to lowercase 
  *  - converted "<br>" to "<br />" to make br xhtml-conform (same would be done with "img") 
  *  - the closing of "</big>" will have do an implicite closing of "<i>" because <big> surrounds "<i>" 
  * 
  * Beware: the output-string is not the most beautiful code possible but hopefully xhtml-conform 
  * 
  * @param string: input string, html-style (as a browser should like it) 
  * @return: xhtml-compatible string 
  * 
  * Version 
  * V1.0, 20090721, rene@pilz.cc, initial-version 
  * 
  * Released under the terms of BSD (http://en.wikipedia.org/wiki/BSD_licenses) 
*/ 
function autoAdjustToXHTML($string)
{ 
	$returnString=""; 
	$string=trim($string); 
	$elementStack=array(); 
	$stackPoint=0; 
	while ($string!="") { 
		$pos=strpos($string,"<"); 
		if ($pos===false) { 
			// no "<" found, return full string and exit while 
			$returnString.=$string;     
			break; 
		} 

		// copy anythink up to the "<" into return string and reduce string 
		$returnString.=substr($string,0,$pos); 
		$string=trim(substr($string,$pos+1)); 

		$tagName=""; 
		// examine tag-name 
		$i=0; $c=""; 
		for (;$i<strlen($string);$i++) { 
			$c=substr($string,$i,1); 
			if (strpos(";<",$c)!==false) continue;    // some chars we ignore 
			if ($c==" "|| $c==">") break; 
			$tagName.=$c; 
		} 

		$tagName=strtolower($tagName);    // convert uppercase  

		// is there a closing tag? 
		if (substr($tagName,0,1)=="/") { 
			// search for the closing ">" and ignore all before 
			$pos=strpos($string,">"); 
			if ($pos===false) $pos=strlen($string); 
			$string=substr($string,$pos+1); 
			// close as many tags up to the given tag 
			while ($stackPoint>0) { 
				 $stackPoint--; 
				 $stackElement=$elementStack[$stackPoint]; 
				 $returnString.="</".$stackElement.">"; 
				 if ($stackElement==$tagName) break;    // nothing more to do in this while 
			} 
			continue;    // this element-Processing is finished so far, continue at 'while ($string!="") {' 
		} 

		// if we are here, we are within a tag (opening tag) 

		// Push tag on stack 
		$elementStack[$stackPoint]=$tagName; 
		$stackPoint++; 

		// add tag to returnString 
		$returnString.="<$tagName "; 

		// search up to ">" 
		$inApo=false;    // within Apostrophes (" or ') 
		$fakeApo=false; 
		$apoChar=""; 
		for (;$i<strlen($string);$i++) { 
			$c=substr($string,$i,1); 
			if ($fakeApo && strpos(" 	",$c)) { 
				 $fakeApo=false; 
				 $returnString.='"'; 
			} 
			if (!$inApo && !$fakeApo && $c=='=' && !strpos(" 	'"",substr($string,$i+1,1))) { 
				 echo "test2=".substr($string,$i+1,1)."---"; 
				 $fakeApo=true; 
				 $returnString.='="'; 
				 $c=""; 
			} 
			if ($c==$apoChar && $inApo) { $inApo=false; $returnString.=$c." "; $c=""; } 
			if ($inApo && $c=="&" && strpos(substr($string,$i).";",";")>5) $c="&amp;"; 
			else if (($c=="'" || $c=='"') && !$inApo) { $inApo=true; $apoChar=$c; } 
			if ($c==">") break; 
			$returnString.=$c; 
		} 

		// new $string is the rest 
		$string=substr($string,$i+1); 
		$returnString=trim($returnString); 

		// check if this has a "/>" at the end 
		$endSlash=(substr($returnString,strlen($returnString)-1)=="/"); 

		// some elements must have a "/" at the end --> Fake it if needed 
		if (($tagName=="br" || $tagName=="img") && !$endSlash) {  
			$returnString.="/";  
			$endSlash=true; 
		} 

		// check if it is a remark-line (<!-- --> trade this as with-endSlash-Tag) 
		if (substr($tagName,0,3)=="!--") { 
			$returnString=trim($returnString); 
			if (substr($returnString,strlen($returnString)-2)!="--") $returnString.=" --"; // make sure remark-line ends with "-->" 
			$endSlash=true; 
		} 

		// again, do we have a end-slash? (or a faked one?) 
		if ($endSlash) $stackPoint--;    // just remove element from stack 

		// and now add the closing ">" 
		$returnString.=">"; 
	} 

	// ok, we are allmost finish, just clean up the elementStack (from last to first) 
	while ($stackPoint>0) { 
		$stackPoint--; 
		$returnString.="</".$elementStack[$stackPoint].">"; 
	} 
	return $returnString; 
} 
php?>
Tags PHP URLDecode XHTML autoAdjustToXHTML number_format Facebook X
Comments 0
Similar posts
  1. To block copy & paste on your blog content
    901
  2. Simple PHP code performance measuring example
    792
  3. Simple PHP calendar
    474
  4. Checking similarity between two strings in PHP
    674
  5. GD library version in PHP
    505
  6. JSON format control in PHP
    692
  7. mysql optimization – if you are using Word Press, do not turn off persistent connection
    592
  8. File downloading function through PHP code
    532
  9. Image file resizing in PHP
    561
  10. Apache server unstable detection and the related server(mysql, apache) restart automatically
    537
  11. PHP Code can know the current OS is windows or not
    584
  12. Function can extract file name in string having full path in PHP
    567
  13. How to create private URL on S3/CloudFront with time-limit ?
    919
  14. Uploading files to Amazon S3 with REST API in PHP
    842
  15. Setup Apache+PHP+MySQL on Centos 6.7
    605
  16. Human readable random string for captchas in PHP
    559
  17. How to get the duration between days in PHP
    423
  18. Date format validation in PHP
    571
  19. PHP function converts new line to BR tag
    560
  20. Email Validation Snipet in PHP
    379
  21. PHP socket programming to get content with post method
    410
  22. Get Remote IP Address in PHP
    498
  23. How to remove HTML tags in text string?
    405
  24. Directory listing in PHP
    512
  25. Seconds to String in PHP
    436
  26. How to load HTML resource on MFC ?
    841
  27. How to delete file on certain path ?
    389
  28. ASCII Artwork Generator from image file
    470
  29. How to limit by Timeout when opening URL ?
    458
  30. How to put timeout when opening URL by fopen ?
    441
  1. What is 302 Found Redirection in HTTP 1.1?
    490
  2. Implementing a Versatile DNS Server in PHP: Handling A, AAAA, CNAME, and TXT Records
    618
  3. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    739
  4. CentOS 7 PHP Apache Kafka: Installation, Examples, and System Diagram
    306
  5. Apache Kafka Explained: Powering Netflix, Building with PHP
    491
  6. Array of arguments passed to script in PHP
    90
  7. Bob Jenkins' One-At-A-Time hashing algorithm in PHP
    52
  8. 32bits simple hash function in PHP
    39
  9. PHP Code Compression Tool by removing whitespace, strips comments - PHP Minifier/Compressor
    1,412
  10. Setup Apache+PHP+MySQL on Centos 6.7
    605
  11. mcrypt missing when using phpMyAdmin on Centos 6.7
    548
  12. PHP Code can know the current OS is windows or not
    584
  13. Checking similarity between two strings in PHP
    674
  14. Simple PHP calendar
    474
  15. Simple PHP code performance measuring example
    792
  16. GD library version in PHP
    505
  17. JSON format control in PHP
    692
  18. mysql optimization – if you are using Word Press, do not turn off persistent connection
    592
  19. File downloading function through PHP code
    532
  20. Image file resizing in PHP
    561
  21. Apache server unstable detection and the related server(mysql, apache) restart automatically
    537
  22. How to set AUTO_INCREMENT ID in mySQL ?
    607
  23. Function can extract file name in string having full path in PHP
    567
  24. How to create private URL on S3/CloudFront with time-limit ?
    919
  25. Parsing XML in PHP
    1,192
  26. Unzip a ZIP file in PHP
    503
  27. Uploading files to Amazon S3 with REST API in PHP
    842
  28. Human readable random string for captchas in PHP
    559
  29. How to get browser information in PHP?
    853
  30. How to get the duration between days in PHP
    423
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    40
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,613
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    244
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    244
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    258
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    217
  30. Understanding Data Lineage
    260