Jump to content

New to PHP please help


unplugged_web

Recommended Posts

I have two xml files, one is generated in real-time by going to a url that contains a php query string and can't be modified at the source in anyway. The other is a file that works perfectly within the site I'm working on, but it needs to contain the data from the other one and ideally be automatically updated at as often as possible.I was told that I need to use PHP to automatically retrive the information from the php query and then put in into the other file. I am very new to PHP, and don't really know where to start.I'd be extremely grateful for any help that anybody could give me.ThanksLucy

Link to comment
Share on other sites

  • Replies 113
  • Created
  • Last Reply

You can use the file_get_contents function to read the contents of the real-time file.$xml = file_get_contents("http://www.....");Once you have the XML data, you can either write it to another file (if you want to save it), or just use it for whatever else the site is doing. It might be better if you just get the real-time data every time instead of reading a local copy.

Link to comment
Share on other sites

[quote name='justsomeguy' post='75737' date='Jul 6 2007, 06:27 PM']You can use the file_get_contents function to read the contents of the real-time file.$xml = file_get_contents("http://www.....");Once you have the XML data, you can either write it to another file (if you want to save it), or just use it for whatever else the site is doing. It might be better if you just get the real-time data every time instead of reading a local copy.[/quote]Thank you for your reply it sounds very helpful. Sorry to sound really stupid, but how would I write that into a php file and could I get it to automatically save the file to the server?ThanksLucy
Link to comment
Share on other sites

This should work. The first few lines are the important part, the other stuff is making sure various things are defined.

<?php$xml = "http://path/to/xml/file.xml";$destination = dirname(__FILE__) . "/saved.xml"; //save the xml in a file called saved in the current folder$data = file_get_contents($xml);if (!$bytes = file_put_contents($destination, $data))  echo "Writing to {$destination} failed";else  echo "Succesfully wrote {$destination}, saved {$bytes} bytes";if (!defined('FILE_APPEND'))  define('FILE_APPEND', 1);if (!function_exists('file_put_contents')){function file_put_contents($n, $d, $flag = false){  $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';  $f = @fopen($n, $mode);  if ($f === false)  {	return 0;  }  else  {	if (is_array($d)) $d = implode($d);	$bytes_written = fwrite($f, $d);	fclose($f);	return $bytes_written;  }}}?>

Link to comment
Share on other sites

This should work. The first few lines are the important part, the other stuff is making sure various things are defined.
<?php$xml = "http://path/to/xml/file.xml";$destination = dirname(__FILE__) . "/saved.xml"; //save the xml in a file called saved in the current folder$data = file_get_contents($xml);if (!$bytes = file_put_contents($destination, $data))  echo "Writing to {$destination} failed";else  echo "Succesfully wrote {$destination}, saved {$bytes} bytes";if (!defined('FILE_APPEND'))  define('FILE_APPEND', 1);if (!function_exists('file_put_contents')){function file_put_contents($n, $d, $flag = false){  $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';  $f = @fopen($n, $mode);  if ($f === false)  {	return 0;  }  else  {	if (is_array($d)) $d = implode($d);	$bytes_written = fwrite($f, $d);	fclose($f);	return $bytes_written;  }}}?>

Thanks for this. The xml feed that I need is coming from http://stats.probability.tv/feed.php?key=<MY KEY> (<MY KEY> is the password for the account), I tried changing this and then uploading the file to the server. I then went to the address to get the code to run. Maybe I'm a bit slow, but it didn't seem to save the xml, I even tried it with an xml file that I created myself. Where should I be saved to? I looked in htdocs, private, logs, cgi-bin and bin, but couldn't find it in any of them. Sorry to make such a nuisance of myself, but I really want to get this sorted.ThanksLucy
Link to comment
Share on other sites

Yeah, I ran into this this weekend on something else. If a function definition is inside an if statement it doesn't get it on the first pass. Just need to reorder the code.

<?phpif (!defined('FILE_APPEND'))  define('FILE_APPEND', 1);if (!function_exists('file_put_contents')){function file_put_contents($n, $d, $flag = false){  $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';  $f = @fopen($n, $mode);  if ($f === false)  {	return 0;  }  else  {	if (is_array($d)) $d = implode($d);	$bytes_written = fwrite($f, $d);	fclose($f);	return $bytes_written;  }}}$xml = "http://path/to/xml/file.xml";$destination = dirname(__FILE__) . "/saved.xml"; //save the xml in a file called saved in the current folder$data = file_get_contents($xml);if (!$bytes = file_put_contents($destination, $data))  echo "Writing to {$destination} failed";else  echo "Succesfully wrote {$destination}, saved {$bytes} bytes";?>

Link to comment
Share on other sites

Thank you, that worked and I got a message saying: e:\domains\t\thephonecasino.com\user\htdocs/saved.xmlOne question though, how do I find that document myself? I've looked int he root folder and typed the address into my browser, but can't find the file?

Link to comment
Share on other sites

That is the full path to the file on the server, so starting at the root of the E drive, you would follow those folders to find the file. It saves it in the same folder as the PHP file, so you can replace the PHP filename with saved.xml to load it in a browser.

Link to comment
Share on other sites

That is the full path to the file on the server, so starting at the root of the E drive, you would follow those folders to find the file. It saves it in the same folder as the PHP file, so you can replace the PHP filename with saved.xml to load it in a browser.
I got a message saying that there was an "error on line 3 at column 6: XML declaration allowed only at the start of the document" I think it because there are a few empty lines at the top of the document, is there anyway I can remove them?
Link to comment
Share on other sites

Change this line:if (!$bytes = file_put_contents($destination, $data))to this:if (!$bytes = file_put_contents($destination, trim($data)))That will trim excess whitespace off the beginning and end of the XML data.

Link to comment
Share on other sites

Change this line:if (!$bytes = file_put_contents($destination, $data))to this:if (!$bytes = file_put_contents($destination, trim($data)))That will trim excess whitespace off the beginning and end of the XML data.
I'm still getting an error, I think that this time it's because one of the attributes has an "!" Is it possible for the php file to take the details I want out of the query string and then save those details into the saved.xml file?Thank you so much for your help, I was really starting get get lost with all of this.
Link to comment
Share on other sites

You can save whatever you want to the file. It's a text file, so any ASCII text you want can be put there.
Sorry to ask so many questions and be a real nuisance, but how would I go about doing that? I'm VERY new to all of this and have never used XML or PHP before, but my boss wants me to get this sorted before he comes back from holiday.
Link to comment
Share on other sites

Well the file_put_contents function will write the text to the file, so whatever text you have there will be saved. Right now the text is a variable called $data, you can add anything you want to $data and it will get written to the file. To access the querystring, you can use the $_GET array. If you have a querystring like this:index.php?varname=some_valueYou would access the value like this:$_GET['varname']If you add that to $data, it will get saved to the file. To add something to the beginning, you would do this:$data = $newval . $data;And to add something to the end would be this:$data .= $newval;

Link to comment
Share on other sites

Well the file_put_contents function will write the text to the file, so whatever text you have there will be saved. Right now the text is a variable called $data, you can add anything you want to $data and it will get written to the file. To access the querystring, you can use the $_GET array. If you have a querystring like this:index.php?varname=some_valueYou would access the value like this:$_GET['varname']If you add that to $data, it will get saved to the file. To add something to the beginning, you would do this:$data = $newval . $data;And to add something to the end would be this:$data .= $newval;
I have two xml files: www.thephonecasino.com/test2.xml (the one you helped me save) and www.thephonecasino.com/Marquee.xml. I want the infomartion in test2.xml to be inputted into Marquee.xml but I'm not too sure if I can get it to look like that or even if I can get it to look anything like that
Link to comment
Share on other sites

If you want to combine two XML documents, then it's considerably more complex. Instead of just writing text data, you need to read the XML structure and parse it up into elements and then combine the two sets of elements and write everything out to a new document.Having not done very much with XML myself, I'll let you borrow this:summon_boen.jpg

Link to comment
Share on other sites

AHAHAHAHA!!!!!!!! :):):):blink::blink: Damn it, I never laughed SOOOO hard in my life. I'm a Yu-Gi-Oh! fan (that's where my previous avatar was from) and being "summoned" with a card (well... "Magic: the gathering card" or something like it, but still) and being THAT literal about it had never crossed my mind :) .Now if I could only stop giggling, I'll get to this issue.... khm...OK. Now, as justsomeguy was pointing (in the card), you could use XSLT to transform your XML into another one appearing just like that other one. You could practically fetch the data from the second one each time.So, here's a nice XSLT that would do the job just fine:

<?xml version="1.0"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">	<xsl:output indent="yes"/>	<xsl:param name="original" select="Marquee.xml"/>	<xsl:template match="/CasinoInfo">		<!--Parameter addded for performance's sake.		Otherwise doable with "../CasinoName" within the for-each-->		<xsl:param name="casino" select="CasinoName"/>		<PhoneCasino>			<xsl:copy-of select="document($original)/PhoneCasino/*"/>			<xsl:for-each select="Games/*">				<Casino>					<CasinoName>						<xsl:value-of select="$casino"/>					</CasinoName>					<Game>						<xsl:value-of select="title"/>					</Game>					<Winner>						<xsl:value-of select="lastWinner"/>					</Winner>					<won>						<xsl:value-of select="about"/>					</won>					<!--There seem to be some games that don't have a jackpot written.					If you want to have empty <Jackpot/> elements, remove this xsl:if element-->					<xsl:if test="jackpot">						<Jackpot>							<xsl:value-of select="jackpot/progressive/penceInteger"/>						</Jackpot>					</xsl:if>				</Casino>			</xsl:for-each>		</PhoneCasino>	</xsl:template>	<!--Just to eliminate some of the extra spaces-->	<xsl:template match="text()">		<xsl:value-of select="normalize-space(.)"/>	</xsl:template></xsl:stylesheet>

That would actually also work perfectly if other casinos were using the same format to present their data. Anyway, for PHP, you'll need this sort of code:

<?php//You can safely put anything else you want here, such as the code to fetch the remote XML for example//Your files. The saved XSLT file and the two XMLs to be more precise. This sample code assumed the XSLT is saved as test2.xsl$xsltFile = 'test2.xsl';$xmlFile = 'test2.xml';$newFile = 'Marquee.xml';//Verify the file paths.if (!file_exists($xmlFile)) {die('No XML file at "' . $xmlFile . '". Verify the file exists and check for spelling mistakes');}if (!file_exists($xsltFile)) {die('No XSLT file at "' . $xsltFile . '". Verify the file exists and check for spelling mistakes');}//Prepare the XML file$xml = new DomDocument;if (!$xml->load($xmlFile)) {die('XML file "' . $xmlFile . '" is not well-formed.');}//Prepare the XSLT file$xsl = new DomDocument;if (!$xsl->load($xsltFile)) {die('XSLT file "' . $xsltFile . '" is not well-formed XML document.');}//Load the XSLT processor$xslt = new Xsltprocessor;$xslt->importStylesheet($xsl);//Tell the XSLT stylesheet the name of your new file$xslt->setParameter(null, 'original', $newFile);//Execute the transformationif (!$xslt->transformToURI($xml, $newFile)) {die('Error during transformation of "' . $xmlFile . '" with  "' . $xsltFile . '" as stylesheet. Possibly an endless loop or illegal XSLT/XPath construct. Other possibilies include disability to write "' . $newFile . '"');}//Optionally present the user with the new file//It might be useful to tell the browser this will be an XML document before everythingheader('Content-type: application/xml');echo file_get_contents($newFile);?>

I haven't tested any of the PHP, but it should work. Do a backup just in case. As you can see, there are also error handlers everywhere in the code, so if you encounter an error, say what message (if any) actually appears.

Link to comment
Share on other sites

Sorry to be so stupid, but I did what you said and it didn't work. I copied all of the xsl test into a new document without changing any of it and the added the php to the file I already had, but it didn't do anything different. I probably just put the code in the wrong place or got it all muddled up. The php now reads:

<?phpif (!defined('FILE_APPEND'))  define('FILE_APPEND', 1);if (!function_exists('file_put_contents')){function file_put_contents($n, $d, $flag = false){  $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';  $f = @fopen($n, $mode);  if ($f === false)  {	return 0;  }  else  {	if (is_array($d)) $d = implode($d);	$bytes_written = fwrite($f, $d);	fclose($f);	return $bytes_written;  }}}$xml = "http://stats.probability.tv/feed.php?key=mypassword";$destination = dirname(__FILE__) . "/saved.xml"; //save the xml in a file called saved in the current folder$data = file_get_contents($xml);if (!$bytes = file_put_contents($destination, trim($data)))  echo "Writing to {$destination} failed";else  echo "Succesfully wrote {$destination}, saved {$bytes} bytes";//Your files. The saved XSLT file and the two XMLs to be more precise. This sample code assumed the XSLT is saved as test2.xsl$xsltFile = 'test2.xsl';$xmlFile = 'test2.xml';$newFile = 'Marquee.xml';//Verify the file paths.if (!file_exists($xmlFile)) {die('No XML file at "' . $xmlFile . '". Verify the file exists and check for spelling mistakes');}if (!file_exists($xsltFile)) {die('No XSLT file at "' . $xsltFile . '". Verify the file exists and check for spelling mistakes');}//Prepare the XML file$xml = new DomDocument;if (!$xml->load($xmlFile)) {die('XML file "' . $xmlFile . '" is not well-formed.');}//Prepare the XSLT file$xsl = new DomDocument;if (!$xsl->load($xsltFile)) {die('XSLT file "' . $xsltFile . '" is not well-formed XML document.');}//Load the XSLT processor$xslt = new Xsltprocessor;$xslt->importStylesheet($xsl);//Tell the XSLT stylesheet the name of your new file$xslt->setParameter(null, 'original', $newFile);//Execute the transformationif (!$xslt->transformToURI($xml, $newFile)) {die('Error during transformation of "' . $xmlFile . '" with  "' . $xsltFile . '" as stylesheet. Possibly an endless loop or illegal XSLT/XPath construct. Other possibilies include disability to write "' . $newFile . '"');}//Optionally present the user with the new file//It might be useful to tell the browser this will be an XML document before everythingheader('Content-type: application/xml');echo file_get_contents($newFile);?>

I looked at the saved.xml file afterwards and it's structure hadn't changed. I also tried going to original.xml, but it said there was no such file.I'm really sorry to cause so many problems and do appreciate all of you help.ThanksLucy

Link to comment
Share on other sites

You're not seeing any error messages? Oh, damn it.... I forgot to mention a key ingredient that's needed to all of this. The XSL extension is not enabled by default and it's needed to perform the XSLT processing.Are you running PHP on a host, or do you run the site on your own computer? If on a host, ask them to "enable the PHP XSL extension" (you could give them the link too, just in case). If you're on your own computer, follow theese instructions.Also, it seems you're "echo"-ing stuff beforehand, so this means the last part of the script should be removed. This one to be more precise:

//Optionally present the user with the new file//It might be useful to tell the browser this will be an XML document before everythingheader('Content-type: application/xml');echo file_get_contents($newFile);

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.


×
×
  • Create New...