Page 1 of 1

PHP Object to XML

Posted: Fri Nov 19, 2010 7:04 am
by kissko86
Hi,

I am currently building a very simple CMS. I am using OOP for generating static pages. However, I am having a problem with storing the objects. Can anyone suggest how can this be done by storing objects into XML files? I have heard of serialization but don't understand that approach completely.

//example of my class

class Page {
private $title;
private $heading;
private $content;

public function Page($t,$h,$c) {
$this->title = $t;
$this->heading = $h;
$this->content = $c;
}

public function getTitle() {
return $this->title;
}

public function getHeading() {
return $this->heading;
}

public function getContent() {
return $this->content;
}
}

//instantiating object

$title = $_POST['title'];
$heading = $_POST['heading'];
$content = $_POST['content'];

$myPage = new Page($title, $heading, $content);

//after this it should be stored as XML file, but don't know how

Thanx in advance.

Re: PHP Object to XML

Posted: Fri Nov 19, 2010 11:49 am
by Jonah Bron
You can just serialize your Page object, XML is probably unnecessary in this case.

Code: Select all

$myPage = serialize($myPage);
file_put_contents('somefile.txt', $myPage);

// later, to get it back,

$myPage = file_get_contents('somefile.txt');
$myPage = unserialize($myPage);
// voilĂ !  Your object is back.
You can look at the contents of the text file to see what your serialized object looks like.

Re: PHP Object to XML

Posted: Mon Nov 22, 2010 1:58 pm
by kissko86
Thanx..that works perfectly. However, I have another question.
As you suggested, the objects (Pages) will be stored in the text file such as about.txt, faq.txt and so on. How can I then iterate through these files to create navigation dynamically?
I know how it could be delivered by using database, but I don't want to use database for these pages.

to explain by what I mean I will give you the example of the database solution.

$result = sqlite_query($db, "SELECT * FROM Page");

while ($row = sqlite_fetch_array($result, SQLITE_ASSOC)) {
echo "<a href='mysie.php?page=" . $row['title'] . ">" . $row['title'] . "</a>";
}

Any ideas for the OO approach?

Thanx in advance

Re: PHP Object to XML

Posted: Mon Nov 22, 2010 2:05 pm
by AbraCadaver

Code: Select all

foreach(glob('pages/*.txt') as $page) {
   $title = str_replace('.txt', '', $page);
   echo "<a href='mysie.php?page=" . $title . ">" . $title . "</a>";
}

Re: PHP Object to XML

Posted: Mon Nov 22, 2010 2:29 pm
by kissko86
Thanx a lot. That works perfectly. :)