0

I want to create a PHP program that could create a .php file that could read this HTML file:

<html>
<head>
<title> Hello World! </title>
</head>
<body>
</body>
</html>

It will search the <head> and </head> TAGS incuding the tags in between, and transfer the selected tags to header.php

So, the header.php will have this:

<head>
<title> Hello World! </title>
</head>

Additional problem is, how to insert the PHP tag <?php in the beginning of the page and ?> in the last part of the PHP file.

I have done this code right here, but its not yet done and i doesn't read a <head> tag.

<?php
firstIdentifier = '<head>';
$secondIdentifier = '</head>';
$currentContent = str_replace("\n", "", file_get_contents('sourcefile.txt'));
$pattern = '/('.$firstIdentifier.')(.+?)('.$secondIdentifier.')/'; 

//get all text between the two identifiers, and include the identifiers in the match result
preg_match_all($pattern, $currentContent , $matches);

//stick them together with space delimiter
$contentOfNewFile = implode(" ",$matches[0]);

//save to a new file
$newFile = fopen('destinationFile.txt','a');
fwrite($newFile, $contentOfNewFile);
?>

Please Help...

cdhowie
  • 158,093
  • 24
  • 286
  • 300
woninana
  • 3,409
  • 9
  • 42
  • 66
  • Obligatory: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – deceze Nov 17 '10 at 05:24

1 Answers1

0

I think you're doing it the hard way. Have you considered parsing HTML as XML using SimpleXML library? You could do that! Allow me to explain:

Suppose you read your file into a string variable called $html_main, now consider this code:

$dom = new DOMDocument("1.0", "UTF-8");
$dom->loadHTML($html_main);

$xml = simplexml_import_dom($dom);

Using XPATH (//html/head) will give you the node, just need to call the function:

$xpathObj = $xml->xpath('//html/head');

Then you can manage your HTML code as a collection! I think that if you are planning doing some major parsing, then this might be a better way!

David Conde
  • 4,631
  • 2
  • 35
  • 48
  • hi david, could you please help me out here. I'm developing a school project, i'm really really confuse about it. what about if i'm gonna a PHP library on this site: http://simplehtmldom.sourceforge.net/ how am i able to solve the problem above? please give m a hint.thanks – woninana Nov 21 '10 at 07:40