Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Saving data as XML

From: Working with Data on the Web

Video: Saving data as XML

If you're working with XML data and you want to go directly from the web to your XML file, this lesson's for you. I'll show you how using PHP to add form values to an existing XML file as an appended node which uses the form element's own IDs to create the XML structure. Now, I've opened the index.php file, from the Chapter three, 0302 folder, It's our basic form, that will submit to itself, as the action is blank. The form starts on line 40.

Saving data as XML

If you're working with XML data and you want to go directly from the web to your XML file, this lesson's for you. I'll show you how using PHP to add form values to an existing XML file as an appended node which uses the form element's own IDs to create the XML structure. Now, I've opened the index.php file, from the Chapter three, 0302 folder, It's our basic form, that will submit to itself, as the action is blank. The form starts on line 40.

Now let's add a php routine that checks for the submit button being clicked and we'll do that right at the top of the page. So I'll add in my php code block and then as the first line, my if statement. If parenthesis is set, then another set of parenthesis to find out what needs to be set and will identify the post array, those are the values coming from our form and specifically the submit button.

So after that lets put in our open and close curly braces. And I'll clean out that extra space there and next we'll set up a couple of variables that we'll need. The name of our XML data file and the name of the main node we'll be inserting. So $file and we'll set that equal to data.xml. Now our main node, which I'm going to call "userNode" because we're gathering a group of users, is "student".

As you'll see, we'll have a collection of students. Now, we'll define a new dom document object, and load our existing file into it. We're also going to need a couple of parameters for formatting. The order in which we put these in is critical. So I'm going to create the variable doc, and use the keyword new DOM document. Make sure you get the upper casing correct there, and put in 1.0 as the version number in single quotes close it off with a semicolon.

Now there are three perimeters for our dom document object. The first one is preserve white space and we'll do doc dash bracket, known collectively as arrow, preserve WhiteSpace. Again, upper and lower case, as shown here. And because I'm not really using a text area, I'm going to set this to false. Next we'll actually load in the file. So, doc arrow load parentheses, $file for our attribute.

Now I know it seems a little odd to do it in this particular order, but there seems to be oh a little bit of hinkiness on the php site here where if you don't exactly do this in this particular linear order, the format won't come out correctly. And that's the next option that we're going to declare doc, arrow, format, output and we'll set that to true. This will ensure that our xml document is formatted properly.

Now the xml file that we're going to be writing into, has a root element already in place, called students. Let's take a look at that right now. Now, you'll notice the comment in between the two. Because of a bug in format output, you can't have a totally empty root element, so I've added a simple comment. All of our data will go right below this comment. Okay, let's head back to the code. Now in order to properly append the nodes we're going to be building, one for each form submitted.

We'll need to create a variable for this root element,that's the one I just showed you which is known as the document element. So '$root', and set that equal to "$doc->documentElement, now, in a moment, we'll put in the code for looping through all the form elements that have been posted. But, we don't actually want all of them. There's no need to grab the submit button. So, we'll use the unset function to remove it from the array.

First, I'm going to set up a little variable to make it easier for us to use post all the time. And now unset, parenthesis, our variable we just created, which is the post array, and then square brackets, single quotes and within that,the name, or ID, of our submit button, submit. Okay, close this all off with a semicolon. Now we're ready to start building our node.

The first one we'll create is the wrapper for all the values. I refer to this as our user node. So we'll first create our element and then append it to the root element. A new variable user, and again we'll go for the doc, arrow create, element, parenthesis user node. And that refers to the variable we declared at the top of this routine.

Now that we've created it we need to bring it into the document by appending it. And we don't append it to the document we append it to the root. This will put it under students and we'll use the append child syntax and what're we appending, user. Okay, now, we're finally ready to loop through the posted form elements and build up our node elements.

We'll use the for each loop to do this. For each parenthesis, and we want to look at the post array, so for each post as $key. And here we use the => $value. So it's for each post as key value. Then after that, {. Now we want to create a new node, so I'm going to give it a variable name of node.

And this is coming from the document. Again, we'll use create element. And this time, we'll pass in two values, key, value. So this will give us our code structure, where the keys that are being written or the custom tags that use the IDs from the form elements, like email or study, and the values are what's entered by the site visitor. Okay, we've created our element, don't forget the semi-colon at the end of that, now lets append the child.

Again we'll use the user variable, arrow, append child and the child we're going to append is the one we just created, node. All right, almost home. All that's left is to save out the new doc with the appended nodes as a string and then, write that to the file. Once that's done, we'll direct to the Thank You page. So, let's go after the for each loop and I'll scroll down a little bit to make it easier to see what's going on.

Now, let's save our doc. So doc, arrow, use the save function, parenthesis, what we're saving is to the file name that we initially created and we'll put in a little arrow handling here or die, if it doesn't work and lets give it a quote of, "sorry there's a problem saving the file.".

Okay, we've saved the document, now lets redirect the page. Using the header function, in single quotes, "location thanks.php". Alright, lets save our revised code, and see if it flies. I'm going to browse to my form page and then hit refresh to make sure all of my code is in place. Let's scroll down a tad. Now let's fill out the form and click submit.

This time I'll go in as Joey, and let's use that standard email address. I think I have a couple of pseudo-cellphone numbers there! Now I should demonstrate that we do have a calendar available here because we're in Chrome. So I can pick a date. Now I'm not going to scroll all the way back to my birth year, that would not really be fun for anybody, but let's just go in here and change the date a little bit change that value and click submit.

Well looking good so far we've got our thank, you so let's go take a look at our data xml file. I'll scroll to that, I see that it's been changed. I'll click yes to see it. And there's our data. As you can see, we have students, and then the first student is listed starting on line four, and it goes all the way down to line ten. That's one node. Each of the elements inside it pick up the name of the custom xml tag from the ID of the form element.

We have name, email, cell, dob, short for date of birth, and study, and all the data that we entered. And best of all, it's all nicely formatted. Well, now that you've seen how to write out xml data, you're ready to see how to bring it back in to your webpage.

Show transcript

This video is part of

Image for Working with Data on the Web
Working with Data on the Web

25 video lessons · 10134 viewers

Joseph Lowery
Author

 

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Working with Data on the Web.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.