php string into xml file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
blade_922
Forum Contributor
Posts: 132
Joined: Wed Jul 12, 2006 4:57 pm

php string into xml file

Post by blade_922 »

Hey there,

I already have a xml file with the following

Code: Select all

- <item>
  <photo>images/01.jpg</photo> 
  <h1>Headline One Goes Here</h1> 
  <p>Put text here. You can add 2 lines max Put text here. You can add 2 lines max Put text here. You can add 2 lines max Put text here. You can add 2 lines max Put text here. You can add 2 lines max</p> 
  <url>http://www.cnet</url> 
  </item>
What i need to do is read the data from mysql database and insert the info into each of the tags. I know how to read the data into a php file and put each of the different tags like photo, url, etc into strings like $photo and $url. So i know how to do it in a php file, but how do i get those strings to appear in an xml file that i already have set up?

Regards
Bon Bon
Forum Commoner
Posts: 66
Joined: Sat Mar 13, 2004 10:21 pm
Location: UK

Post by Bon Bon »

I have quickly put together a function that will do the trick:

Code: Select all

function extract_xml_content ($tag, $xml) {
  if (preg_match('/<$tag>(.*)</$tag>/s', $xml, $matches)) {
    return $matches[1];
  }
  else return FALSE;
}
Last edited by Bon Bon on Mon Sep 03, 2007 6:45 am, edited 1 time in total.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

You can also use php5's simplexml extension (or DOM).

Code: Select all

<?php
$row = array(
	'photo' => 'images/01.jpg',
	'headline' => '-->Headline One Goes Here<--',
	'text' => 'Put text here. You can add 2 lines max Put text here. You can add 2 lines max Put text here. You can add 2 lines max Put text here. You can add 2 lines max Put text here. You can add 2 lines max'
);

$item = new SimpleXMLELement('<item />');
$item->photo = $row['photo'];
$item->h1 = $row['headline'];
$item->p = $row['text'];

echo $item->asXML();
?>
it will e.g. take care of the proper encoding of the document; in this case
<h1>-->Headline One Goes Here<--</h1>
Post Reply