Solved

Adding or Writing to XML with PHP

Posted on 2008-11-02
13
856 Views
Last Modified: 2010-05-18
Hello,

I am new to PHP, and going through it slow.
Here is my question.

I am currently using the attached PHP code to add or write data to an XML.

Here is what the PHP is currently creating.
<?xml version="1.0" encoding="UTF-8"?>
<guestbook>
<item nome="
rootz" eMail="rock
" messaggio="roll
"></item>
</guestbook>
<?xml version="1.0" encoding="UTF-8"?>
<guestbook>
<item nome="hi
" eMail="roots
" messaggio="rock
"></item>
</guestbook>

What I would like to accomplish is,  when the PHP adds the new data to the XML it is only adding the line,

Write_to_file("<item nome=\"$strNome\" eMail=\"$strEmail\" messaggio=\"$strCommento\"></item>"."\n");

in between the header and the footer and not adding them every time.

Here is an example of what I want.
<?xml version="1.0" encoding="UTF-8"?>
<guestbook>
<item nome="
rootz" eMail="rock
" messaggio="roll
"></item>
<item nome="hi
" eMail="roots
" messaggio="rock
"></item>
</guestbook>

How can I accomplish this?

Thank you.
<?php
 
        $strNome = $_POST['nome'];
        $strEmail = $_POST['email'];
        $strCommento = $_POST['commento'];
 
function Write_to_file($text){
 
        $dir='xml/';
        $file="images.xml";
        $filepath= $dir. $file;
        $connect = fopen($filepath, 'a+');
        $write = fwrite($connect, $text);
        fclose($connect);
 
        }
 
 
        Write_to_file("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"."\n");
        Write_to_file("<guestbook>"."\n");
 
        Write_to_file("<item nome=\"$strNome\" eMail=\"$strEmail\" messaggio=\"$strCommento\"></item>"."\n");
 
        Write_to_file("</guestbook>"."\n");
 
        $dir='xml/';
        $file="images.xml";
        $filepath= $dir. $file;
 
        if(file_exists($filepath)){
 
        echo "answer=true";
 
        }

Open in new window

0
Comment
Question by:quetzali
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 5
13 Comments
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 22861979
You can't do that. You would have to read the file into memory, remove the last line, add your new item, and add the last line again, and write the file. Something like this:
function AppendToXML($file,$newItem) {
  $data = file_get_contents($file);
  $lines = explode("\n",$data);
  $lastline = array_pop($lines);
  $lines[] = $newItem;
  $lines[] = $lastline;
  $data = implode("\n",$lines);
  file_put_contents($file,$data);
}
 
AppendToXML('test.xml',"<item nome=\"$strNome\" eMail=\"$strEmail\" messaggio=\"$strCommento\"></item>");

Open in new window

0
 

Author Comment

by:quetzali
ID: 22862245
Thanks cxr,

I am new to PHP and  I am having trouble adding your lines of code.

Can you give me a few more instructions on how to implement the code?

Does it replace the code I already have or should it be included along with it?

Thanks for your help.
0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 22862492
You can integrate it in your code like below. The xml file must exist.
<?php
 
function AppendToXML($file,$newItem) {
  $data = file_get_contents($file);
  $lines = explode("\n",$data);
  $lastline = array_pop($lines);
  $lines[] = $newItem;
  $lines[] = $lastline;
  $data = implode("\n",$lines);
  file_put_contents($file,$data);
}
 
$strNome = $_POST['nome'];
$strEmail = $_POST['email'];
$strCommento = $_POST['commento'];
 
$dir='xml/';
$file="images.xml";
$filepath= $dir. $file;
 
AppendToXML($filepath,"<item nome=\"$strNome\" eMail=\"$strEmail\" messaggio=\"$strCommento\"></item>");
 
if(file_exists($filepath)){
  echo "answer=true";
}
 
?>

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:quetzali
ID: 22862657
Thanks again cxr,

Unfortunately It doesn't seem to add or append the XML for me?

I have used your code exactly how you have it above.

The XML file is in place.

Any ideas why it wouldn't work for me?

Much appreciated.
0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 22863174
Insert PHP error checking, report back with any errors.
<?php
ini_set('display_errors', 1);   # enable PHP error reporting
error_reporting(E_ALL);
 
function AppendToXML($file,$newItem) {
  $data = file_get_contents($file);
  $lines = explode("\n",$data);
  $lastline = array_pop($lines);
  $lines[] = $newItem;
  $lines[] = $lastline;
  $data = implode("\n",$lines);
  file_put_contents($file,$data);
}
 
$strNome = $_POST['nome'];
$strEmail = $_POST['email'];
$strCommento = $_POST['commento'];
 
$dir='xml/';
$file="images.xml";
$filepath= $dir. $file;
 
AppendToXML($filepath,"<item nome=\"$strNome\" eMail=\"$strEmail\" messaggio=\"$strCommento\"></item>");
 
if(file_exists($filepath)){
  echo "answer=true";
}
 
?>

Open in new window

0
 

Author Comment

by:quetzali
ID: 22863379
Great I did that and this is the error that comes up,


Fatal error: Call to undefined function: file_put_contents() in /home/content/a/m/e/americancuervo/html/uploader/writetoxml.php on line 12

Thanks again
0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 22863554
Ok, you are using php4, file_put_contents() was added in php5. This is easily fixed:
<?php
ini_set('display_errors', 1);   # enable PHP error reporting
error_reporting(E_ALL);
 
function My_file_put_contents($filename, $data) {
  $f = fopen($filename,'w');
  if(!$f) die("Can not open file '$file' for writing");
  fwrite($f,$data);
  fclose($f);
}
 
function AppendToXML($file,$newItem) {
  $data = file_get_contents($file);
  $lines = explode("\n",$data);
  $lastline = array_pop($lines);
  $lines[] = $newItem;
  $lines[] = $lastline;
  $data = implode("\n",$lines);
  My_file_put_contents($file,$data);
}
 
$strNome = $_POST['nome'];
$strEmail = $_POST['email'];
$strCommento = $_POST['commento'];
 
$dir='xml/';
$file="images.xml";
$filepath= $dir. $file;
 
AppendToXML($filepath,"<item nome=\"$strNome\" eMail=\"$strEmail\" messaggio=\"$strCommento\"></item>");
 
if(file_exists($filepath)){
  echo "answer=true";
}
 
?>

Open in new window

0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 22863561
Change the error message in the new function, it should be $filename, not $file:

"Can not open file '$filename' for writing"
0
 

Author Comment

by:quetzali
ID: 22863661
Thanks cxr,

It's writing to the XML now.

Attached below is the output to the XML from the PHP.

It unfortunately doesn't place the necessary footer </guestbook> at the bottom underneath the new data.
Instead it remains in the same place.

Is this possible to do?

Thanks again for your help.
<?xml version="1.0" encoding="UTF-8"?>
<guestbook>
<item nome="rasta
" eMail="fari
" messaggio="siempre
"></item>
</guestbook>
<item nome="JAH
" eMail="irie
" messaggio="always
"></item>
<item nome="juana
" eMail="tortuga
" messaggio="buena
"></item>

Open in new window

0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 22863717
It seems all your values has a linefeed at the end... where does that come from?

First, lets fix the xml file. Overwrite your current xml file with this version:
<?xml version="1.0" encoding="UTF-8"?>
<guestbook>
<item nome="rasta" eMail="fari" messaggio="siempre"></item>
<item nome="JAH" eMail="irie" messaggio="always"></item>
<item nome="juana" eMail="tortuga" messaggio="buena"></item>
</guestbook>

Open in new window

0
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 500 total points
ID: 22863758
Then we fix the script so that it removes trailing (and leading) spaces, using the PHP trim() function. You are saving all the values as attributes in the xml, so they can also not contain any " (double quote) character, they must be encoded as &quot;. We can make a special function for handling both issues. Let's call it FetchInput():
<?php
ini_set('display_errors', 1);   # enable PHP error reporting
error_reporting(E_ALL);
 
function My_file_put_contents($filename, $data) {
  $f = fopen($filename,'w');
  if(!$f) die("Can not open file '$file' for writing");
  fwrite($f,$data);
  fclose($f);
}
 
function AppendToXML($file,$newItem) {
  $data = file_get_contents($file);
  $lines = explode("\n",$data);
  $lastline = array_pop($lines);
  if(!trim($lastline))  # the last line was blank!
    $lastline = array_pop($lines);
  $lines[] = $newItem;
  $lines[] = $lastline;
  $data = implode("\n",$lines);
  My_file_put_contents($file,$data);
}
 
function FetchInput($name) {
  return trim(str_replace('"','&quot;',$_POST[$name]));
}
 
$strNome = FetchInput('nome');
$strEmail = FetchInput('email');
$strCommento = FetchInput('commento');
 
$dir='xml/';
$file="images.xml";
$filepath= $dir. $file;
 
AppendToXML($filepath,"<item nome=\"$strNome\" eMail=\"$strEmail\" messaggio=\"$strCommento\"></item>");
 
if(file_exists($filepath)){
  echo "answer=true";
}
 
?>

Open in new window

0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 22863762
argh... fix the error message again:

"Can not open file '$filename' for writing"
0
 

Author Closing Comment

by:quetzali
ID: 31512501
Thanks cxr.
It works perfectly.
0

Featured Post

Secure Your Active Directory - April 20, 2017

Active Directory plays a critical role in your company’s IT infrastructure and keeping it secure in today’s hacker-infested world is a must.
Microsoft published 300+ pages of guidance, but who has the time, money, and resources to implement? Register now to find an easier way.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to dynamically set the form action using jQuery.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

735 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question