Jump to content

Advanced Writing To File


IanArcher

Recommended Posts

I am trying to write to this file herehttp://corporate.the...h/questions.htm I when i add it keeps going of the the html tags and the text ends up under </html> and also to to make the question bold just like on that page, and the answer Bold as in the same style as the answers on that page as well. Title is the question and description is the answer.And also each question has an id , so i want a question to be like <a id="Question33">Can somebody write me a sample of this please? Btw this is a snippet i am including in another set of code that supports and recognizes the functions.

<?php $myFile = "questions.htm";$fh = fopen($myFile, 'a') or die("can't open file");$stringData = $_POST ['title'];$stringData = $_POST ['description']; fwrite($fh, $stringData);fclose($fh); ?>

Link to comment
Share on other sites

That's because you're appending the content to the end of the file. If you want to add something between the content of the file, you're going to have to extract the file data, manipulate it, and then put it back in overwriting the original content. You could use the DOMDocument() class to manipulate it, or just plain string methods, using strpos() and other methods to cut up the string, add pieces and glue it back together.

Link to comment
Share on other sites

That's because you're appending the content to the end of the file. If you want to add something between the content of the file, you're going to have to extract the file data, manipulate it, and then put it back in overwriting the original content. You could use the DOMDocument() class to manipulate it, or just plain string methods, using strpos() and other methods to cut up the string, add pieces and glue it back together.
Could you write me an example please?
Link to comment
Share on other sites

My document is herehttp://corporate.thechamberteam.com/livesearch/questions.htm and i need to put it after the last question and answer or it could go before and after any other question and answer combo in the document. Doesn't really matter as long as it has it's own ID such as "Question33"

Link to comment
Share on other sites

First use file_get_contents to read the entire contents of the file. If you want to put the new content before '</body>', then one method is to use the explode function to split the file contents up into 2 pieces, what comes before '</body>' and what comes after it. You can append your content to the first part, then join the two pieces back together and use file_put_contents to save back to the file. If you want to put the new content somewhere other than just before '</body>', then one method is to use the strrpos function to find the last string that you want to insert before and then use the substr function to get the text before what you want to insert, add the new content, and use substr again to get the text after, join them together and write them to the file. http://www.php.net/m...et-contents.phphttp://www.php.net/m...ion.explode.phphttp://www.php.net/m...ion.strrpos.phphttp://www.php.net/m...tion.substr.phphttp://www.php.net/m...ut-contents.php We're happy to help you with your code, but you'll need to get started first and ask questions when you have them. All of those manual pages contain examples about how to use those functions. If you don't understand something then say what you don't understand.

Link to comment
Share on other sites

Ok, thanks for the assistance so far, but let me explain more in depth.Here is the code that adds a question to the database (Not the page, i want it to add it to the page as well) and This is the page itself > http://corporate.the...search/list.php

<?php$hostname = "localhost"; // usually is localhost, but if not sure, check with your hosting company, if you are with webune leave as localhost$db_user = "root"; // change to your database password$db_password = ""; // change to your database password$database = "search"; // provide your database name$db_table = "searchengine"; // leave this as is error_reporting (E_ALL ^ E_NOTICE); # STOP HERE##################################################################### THIS CODE IS USED TO CONNECT TO THE MYSQL DATABASE$db = mysql_connect($hostname, $db_user, $db_password);mysql_select_db($database,$db);?><html><head><title>Add a Question and Answer to the Database</title><style type="text/css">.style1 {	font-family: Calibri;	font-weight: normal;	font-size: medium;}.style2 {	color: #808080;}.style3 {	text-align: center;}.style4 {	border-width: 0px;}</style></head><body> <?phpif (isset($_REQUEST['Submit'])) {# THIS CODE TELL MYSQL TO INSERT THE DATA FROM THE FORM INTO YOUR MYSQL TABLE$sql = "INSERT INTO $db_table(title,description,url,keywords) values ('".mysql_real_escape_string(stripslashes($_REQUEST['title']))."','".mysql_real_escape_string(stripslashes($_REQUEST['description']))."','".mysql_real_escape_string(stripslashes($_REQUEST['url']))."','".mysql_real_escape_string(stripslashes($_REQUEST['keywords']))."')";if($result = mysql_query($sql ,$db)) {echo '<h1>Thank you</h1>Your information has been entered into our database<br><br>';} else {echo "ERROR: ".mysql_error();}} else {?><h1 class="style3"><a href="index.php"><img src='ChamberLogo.png' class="style4"></a> </h1><h1 class="style1">Add A Question to the FAQDatabase</h1><hr><form method="post" action="">		  Question:<br>         <input type="text" name="title" style="width: 486px"><br>          Answer: <br>         <input type="text" name="description" style="height: 24px; width: 352px"><br>		  Keywords <span class="style2">(Type Question Again):</span><br>         <input type="text" name="keywords" style="height: 24px; width: 486px"><br><br>         <input type="submit" name="Submit" value="Submit"></form><?php}?></body></html>

I tried using a script myself that will just take the title (question) and description (answer) and post it to the questions.htm (http://corporate.the...h/questions.htm) page as well with the formatting of the other questions on the question and answers page a question uses the class style1 and an answer uses the class style2. I also want there to be a break <br> between the question and answer such.

<?php $myFile = "questions.htm";$fh = fopen($myFile, 'a') or die("can't open file");$stringData = $_POST ['title'];fwrite($fh, $stringData);fclose($fh); ?>

An example of a code i imagine in my head is

 $myFile = "questions.htm";$fh = fopen($myFile, 'a') or die("can't open file");$stringData = $_POST .'<br><p class="style1"><a id="Question33">"title"</p></a>'.  $stringData = $_POST .'<br><p class="style2">"description"</p>';fwrite($fh, $stringData);fclose($fh); 

But inserting it in the body tags. Is anyone getting what i'm saying?

Link to comment
Share on other sites

First use file_get_contents to read the entire contents of the file. If you want to put the new content before '</body>', then one method is to use the explode function to split the file contents up into 2 pieces, what comes before '</body>' and what comes after it. You can append your content to the first part, then join the two pieces back together and use file_put_contents to save back to the file. If you want to put the new content somewhere other than just before '</body>', then one method is to use the strrpos function to find the last string that you want to insert before and then use the substr function to get the text before what you want to insert, add the new content, and use substr again to get the text after, join them together and write them to the file.
I've read through the manuals and i actually tried some code in my post above.
$myFile = "questions.htm";$fh = fopen($myFile, 'a') or die("can't open file");$stringData = $_POST .'<br><p class="style1"><a id="Question33"><strong>"title"</strong></a></p>';  $stringData = $_POST .'<br><p class="style2"><o:p>"description"</o:p></p>';fwrite($fh, $stringData);fclose($fh);

But all that does is add this text to the bottom Array"description"Array"description" I don't want it to add the field name, i want it to add what is typed in the form and to go with the bolding formatting and thee <br> tags and classes i specified in my above code. Also i have no idea why it adds description twice instead of even Array"title"Array"description" Can you show me an example code using your recommendation from your post please?

Link to comment
Share on other sites

You're still using fopen to append to the file, which means the new content is still going to show up at the end of the file. You need to use one of the methods I described if you want to add it to the middle of the file. $_POST is an array of data, that's why it prints "Array". If you want to print a single item from $_POST then you need to use the name of the item you want. It only adds description because you overwrite the first line with the second line instead of combining them. It's putting the text "description" there because that's all you're telling it to do, you're not telling it to use a variable. If the description is in $_POST, and the name is "description", then you access it using $_POST['description']. But, if you're adding this information to the database anyway, then why don't you just make the QA page get the questions and answers from the database and write them out dynamically instead of trying to modify a static HTML file? What happens if one of the questions or answers changes, how are you planning on updating the static page?

Link to comment
Share on other sites

Ok this is what i didDivided the questions.htm file into two files, 1st file(questions_layout.php) - to hold the layout of the page WITHOUT the questions and answers, 2nd file(questions_and_answers.htm) - to hold ONLY the questions and answers. Now when I run questions_layout.php from the browser, questions_and_answers.htm will be automatically included between the body tags of the questions_layout.php.Here is my code:

<?php    $myFile = "questions_and_answers.htm";    $fh = fopen($myFile, 'a') or die("can't open file");    $stringData .= "<br><p style='font-size:18px; font-family: Calibri; font-weight: bold;'><a id='Question35'>".$_POST['title']."</p></a>";    $stringData .= "<p style='font-family: Calibri; font-size:16px;'>".$_POST['description']."</p>";    fwrite($fh, $stringData);    fclose($fh);?>

My last problem is,I need to use the same form to write to the XML file that manages the live search results.//I'm appending, not writing, It has to be inserted before </pages> tag, because if it is entered after that the XML code gives an error in the livesearch results.//And also needs the necessary breaks as they presently are in the the XML file, because the XML cant have tags next to each other, they must be on another line.//How i imagine the code for writing the data from the form to the XML file in my head:

<?php    $xmlFile = "links.xml";    $fh = fopen($xmlFile, 'a') or die("can't open file");    $data .= "<link>";    $data .= "<title>".$_POST['title']."</title>";    $data .= "<url>questions_layout.php#".$_POST['id']."</url>";    $data .= "</link>";    fwrite($fh, $data);    fclose($fh);?>

I'ved looked for solutions and this is what i tried

<?php$xml = simplexml_load_file('test.xml');$vote = $xml->addAttribute('link', '');$vote = $xml->addChild('title', '['title']');$vote = $xml->addChild("url", "['url']");$fp = fopen('test.xml', 'w');fwrite($fp, $xml->asXML());fclose($fp);?>

But that just gives me a T_STRING error.The XML File

<?xml version="1.0" encoding="utf-8"?><!-- Edited by XMLSpy® --><pages><link><title>Q: I have local web developers as members, why don’t I just have them build me a website that can do this?</title>Q:<url>questions_layout.php#Question1</url></link><link><title>Q: Do I have to change my domain name?</title>Q:<url>questions_layout.php#Question2</url></link><link><title>Q: What if I want to make changes to the look of the site over time?</title>Q:<url>questions_layout.php#Question3</url></link><link></pages>

Could someone help me on this last part please?

Link to comment
Share on other sites

what am i doing wrong in the code?

<?php$xml = simplexml_load_file('test.xml');$vote = $xml->addAttribute('link', '');$vote = $xml->addChild('title', '['title']');$vote = $xml->addChild("url", "['url']");$fp = fopen('test.xml', 'w');fwrite($fp, $xml->asXML());fclose($fp);?> 

Or should it be:

<?php$xml = simplexml_load_file('test.xml');$vote = $xml->addAttribute('link', '');$vote = $xml->addChild('title', .$_POST.'['title']');$vote = $xml->addChild('url', .$_POST.'['url']');$fp = fopen('test.xml', 'w');fwrite($fp, $xml->asXML());fclose($fp);?>

Link to comment
Share on other sites

The quotes on the title line are not correct. Again, compare the title line with the URL line. They use different quotes. The url line is correct, the title line is not. Even so, that's going to print the text "['url']", not the value from the form. Check posts 1, 10, and 11 to see examples of accessing items inside $_POST.

Link to comment
Share on other sites

Now here is my current code:

<?php //This line will load the XML file.$xml = simplexml_load_file("test.xml"); //In this line it create a SimpleXMLElement object with the source of the XML file.$sxe = new SimpleXMLElement($xml->asXML()); //The following lines will add a new child and others child inside the previous child created.$person = $sxe->addChild("link");$person->addChild("title", "['title']");$person->addChild("url", "['url']#$_POST['id']"); //This next line will overwrite the original XML file with new data added$sxe->asXML("test.xml"); ?>

I followed what you said and you're right about it printing the text "['url']". My dilemma is, still trying to get it to post the actual data entered in the form to the XML file, but in this array for exampletitle = questionurl = url of questions_and_answers.htmid = ID of the question on the above page. i need it to add in the <url></url> tags, questions_and_answers.htm#Question35 So it would display as

<link><title>Q: Sample Question</title><url>questions_and_answers.htm#Question35</url></link>

Could you show me a code example on how i could achieve this?

Link to comment
Share on other sites

I think you need to understand how arrays (in this case an associative array works). POST is just like any other array, except that it is super global, so that is accessible anywhere. In order to access the values of members in an associative array, you would write

$array['key'];  //obviously this is just an example

so, in your case, any value you want must be written in the format

$_POST['key']

be it title, url, or whatever inputs you have in your form, as dictated by the name attribute you define in the HTML. http://www.w3schools.com/php/php_arrays.asphttp://www.w3schools.com/php/php_post.asp

Link to comment
Share on other sites

Ok i took your advice justsomeguy and thescientist and it works and writes to the xml file. This is my code:

<?php //This line will load the XML file.$xml = simplexml_load_file("links.xml");//In this line it create a SimpleXMLElement object with the source of the XML file.$sxe = new SimpleXMLElement($xml->asXML());//Variables$title = ($_POST['title']);$url = ($_POST['url']);$id = $_POST['id'];//The following lines will add a new child and others child inside the previous child created.$person = $sxe->addChild("link");$person->addChild("title", $_POST['title']);$person->addChild("url", "questions_and_answers.htm#$id");//This next line will overwrite the original XML file with new data added$sxe->asXML("links.xml");?>

The thing is, the results are duplicated in the XML file like so

<link><title/><url>questions_and_answers.htm#</url></link>−<link><title>Question</title><url>questions_and_answers.htm#Question39</url></link>

What went wrong?

Link to comment
Share on other sites

You're adding... you're not replacing an existing node. Isn't that what you want?If you want to edit instead, you need to target the nodes you wish to edit and edit them.With SimpleXML, I believe the way to do it was:

<?php //This line will load the XML file.$xml = simplexml_load_file("links.xml");//This line will get the first link from the XML document.$link = $xml->pages->link[0];$link->title = $_POST['title'];$link->url = "questions_and_answers.htm#$id";//This next line will overwrite the original XML file with new data REPLACING THE OLD ONE$xml->asXML("links.xml");

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...