Solved

Adding or Writing to XML with PHP

Posted on 2008-11-02
13
846 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
  • 8
  • 5
13 Comments
 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:quetzali
Comment Utility
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
Comment Utility
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
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
argh... fix the error message again:

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

Author Closing Comment

by:quetzali
Comment Utility
Thanks cxr.
It works perfectly.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

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…
This article discusses how to create an extensible mechanism for linked drop downs.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

743 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now