Page 1 of 1

php string into xml file

Posted: Sun Sep 02, 2007 1:56 pm
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

Posted: Sun Sep 02, 2007 2:04 pm
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;
}

Posted: Sun Sep 02, 2007 2:41 pm
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>