XML & php Blog




XML & php Blog tutorial

The XML part of the blog looks like this:

<?xml version="1.0" encoding="utf-8"?>
<blogs>
<blog>
<heading></heading>
<content></content>
<date></date>
</blog>
</blogs>

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

<?php
if(isset($_POST['publish'])){
$html = publish();
}else{
$html = show_form();
}
$html .= show_blog();

function show_form(){
$out ="<form method=\"post\" action=\"\">
<fieldset>
<legend>Blog</legend>
<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\"/>
</fieldset>
</form>";
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;
}

//NEW DOCUMENT!!
$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>
<p>$content</p>
<p>$date</p>";
}
?>

 

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.

<?php
echo $html;
?>