XML & php Blog

XML & php Blog tutorial

The XML part of the blog looks like this:

<?xml version="1.0" encoding="utf-8"?>

The XML code should be put in a file called blogs.xml


The php code has to be placed in the top of the document, before the HTML.
This php document should be called blogs.php

$html = publish();
$html = show_form();
$html .= show_blog();

function show_form(){
$out ="<form method=\"post\" action=\"\">
<label for=\"heading\">Heading</label>
<input type=\"text\" name=\"heading\" id=\"heading\"/>
<label for=\"html\"><br/></label>
<label for=\"message\">Content</label>
<textarea name=\"content\" id=\"content\" rows='4' cols='40'></textarea>
<input type=\"submit\" name=\"publish\" value=\"publish\"/>
return $out;
function publish(){
$file = "blogs.xml";

//simplexml_load_file — Interprets an XML file into an object
$xml = simplexml_load_file($file);

$new_blog = $xml -> addchild("blog");

$heading = $_POST['heading'];
$new_blog -> addchild("heading", $heading);

$content = $_POST['content'];
$new_blog ->addchild("content", $content);

$date = date('j n Y') ;
$new_blog ->addchild("date", $date);

file_put_contents($file, $xml->asXML());
$url = "blogs.php"; // name of the document containing this code.
$out = "<h3>Posted!</h3>";
$out .="<pre>$heading - $content - $date</pre>";
$out .= "<pre><a href=\"$url\"> Go to blog</a></pre>";
return $out;

function show_blog(){
$file = "blogs.xml";
$xml = simplexml_load_file($file);

//get <heading> from xml and use it as $data
$heading = $xml -> blog -> heading;
$date = $xml -> blog -> date;
$content = $xml -> blog -> content;

//build form
$html = "<p class=\"blog\">".$heading. "\n <br />";
$html .= "\n <br />";
$html .= $content. "\n <br />";
$html .= $date."</p>";
return $html;

$file = "blogs.xml";
$xml = simplexml_load_file($file);

foreach($xml -> blog as $blog){
$heading = $blog -> heading;
$content = $blog -> content;
$date = $blog -> date;
$html .= "<h3>$heading</h3>


And in the body of the HTML you only have to write this small piece of php to make the input form visible and get the blogged text from the XML displayed.

echo $html;