I am pulling in weather data from a Yahoo weather RSS feed for both London and New York. I'm trying to reduce code duplication by reusing a PHP file which contains functions for pulling in the weather data.
Below is the function I am calling - get_current_weather_data(). This function goes off to various other functions such at the get_city() and get_temperature() functions.
<?php
function get_current_weather_data() {
// Get XML data from source
include_once 'index.php';
$feed = file_get_contents(if (isset($sourceFeed)) { echo $sourceFeed; });
// Check to ensure the feed exists
if (!$feed) {
die('Weather not found! Check feed URL');
}
$xml = new SimpleXmlElement($feed);
$weather = get_city($xml);
$weather = get_temperature($xml);
$weather = get_conditions($xml);
$weather = get_icon($xml);
return $weather;
}
In my index.php I set the URL for the RSS feed as the variable called $sourceFeed.
<?php
$tabTitle = ' | Home';
$pageIntroductionHeading = 'Welcome to our site';
$pageIntroductionContent = 'Twinz is a website which has been created to bring towns together!
Our goal is to bring communities around the world together, by providing
information about your home town and its twin town around the world. Our
site provides weather, news and background information for London and
one of its twin cities New York.';
$column1Heading = 'Current Weather for New York';
$column2Heading = 'Current Weather for London';
$column3Heading = 'Current Weather for Paris';
$sourceFeed = "http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f";
include_once 'header.php';
include_once 'navigationMenu.php';
include_once 'threeColumnContainer.php';
include_once 'footer.php';
?>
I attempt to call the feed in my get_current_weather_data() function using:
(if (isset($sourceFeed)) { echo $sourceFeed; }).
However, I receive the following error
"Warning: file_get_contents() [function.file-get-contents]: Filename cannot be empty in C:\xampp\htdocs\Twinz2\nyWeather.php on line 10
Weather not found! Check feed URL".
If I replace
(if (isset($sourceFeed)) { echo $sourceFeed; })
with the URL for the feed it works but this will stop me from reusing the code. Am I trying to do the impossible or is my syntax just incorrect?
This isset method works fine where used elsewhere like for example the $tabTitle and
$pageIntroductionHeading variables just need for the RSS feed.
Thanks in advance.
The problem is in the following line:
$feed = file_get_contents(if (isset($sourceFeed)) { echo $sourceFeed; });
it has to be:
if(isset($sourceFeed)){ $feed = file_get_contents($sourceFeed); }
And when you call the function, you also have to pass $sourceFeed as function parameter, like that:
get_current_weather_data($sourceFeed);
You're attempting to access a global variable $sourceFeed inside your function. Pass it as a parameter to the function instead:
// Pass $sourceFeed as a function parameter:
function get_current_weather_data($sourceFeed) {
// Get XML data from source
include_once 'index.php';
$feed = file_get_contents($sourceFeed));
// Check to ensure the feed exists
if (!$feed) {
die('Weather not found! Check feed URL');
}
$xml = new SimpleXmlElement($feed);
$weather = get_city($xml);
$weather = get_temperature($xml);
$weather = get_conditions($xml);
$weather = get_icon($xml);
return $weather;
}
And call the function as:
$sourceFeed = "http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f";
$weather = get_current_weather_data($sourceFeed);
Try to make $sourceFeed global like this:
function get_current_weather_data() {
global $sourceFeed
OR
get_current_weather_data($sourceFeed)
Your issue is a variable scope issue. The variable that goes inside of the function is a new variable that is used only for the function. It will inaccessible once the function is returned/completed. So, you need to let the function know what the value is:
function get_current_weather_data( $sourceFeed ) { // this tells the function to
// read that variable when it starts. You also need to pass it when you call the function.
get_current_weather_data( $sourceFeed );
// OR
get_current_weather_data( 'http://myurl.com' );
isset($sourceFeed) will always return false. you are using it in a local scope whereas you define it in the global scope. please read more on variable scopes at http://tr2.php.net/manual/en/language.variables.scope.php.
I am fairly sure that what you have done there will not even parse. It certainly won't parse in PHP 5.2.
$feed = file_get_contents(if (isset($sourceFeed)) { echo $sourceFeed; });
This is not valid. You cannot place an if statement inside a call to a function, and even if that did work, it would not affect the way the function is called.
You can use a ternary expression:
$feed = file_get_contents((isset($sourceFeed)) ? $sourceFeed : '');
...but even this will not help you here, since you have to pass a filename to file_get_contents() or you will get the error you see.
Your approach to this is all wrong, rather than including index.php to define your variable, you should pass the variable to the function as an argument. For example:
function get_current_weather_data($sourceFeed) {
// Get XML data from source
$feed = file_get_contents($sourceFeed);
// Check to ensure the feed exists
if (!$feed) {
die('Weather not found! Check feed URL');
}
$xml = new SimpleXmlElement($feed);
$weather = get_city($xml);
$weather = get_temperature($xml);
$weather = get_conditions($xml);
$weather = get_icon($xml);
return $weather;
}
Related
I was wandering if it were possible to store a html schema page with special strings to replace with variable and how to do it.
In an external file, I would like to put the html structure of a product, let's call it schema.php:
<span id="{% id %}">{%= name %}</span>
<span>{%= imageURL() %}</span>
The example above is just a simpler example. In the external file, the html would be more complex. I know that if there were just few lines I could just echo them with a simple function but this is not the case.
In another file I have a class that handle products, let's call it class.php:
class Product {
//logic that is useless to post here.
public function imageURL() {
return "/some/url".$this->id."jpg";
}
}
In this class I would like to add a function that take the content from schema.php and then echo it in the public file for users.
I tried with file_get_contents() and file_put_contents() but it just doesn't work:
$path_to_file = 'data/prodotti/scheda.inc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace(
"{%= ",
"<?php echo $this->",
$file_contents
);
$file_contents = str_replace(
" }",
"; ?>",
$file_contents
);
file_put_contents($path_to_file, $file_contents);
is it possible to call schema.php page and print it with custom variables?
By "schema page" I think you mean "template" and yes, but the best way to do it is to use an existing templating engine such as Smarty or a Mustache implementation like https://github.com/bobthecow/mustache.php instead of implementing it yourself because of the risks of XSS, HTML-injection, and how you'll eventually want features like looping and conditionals.
you can do it normaly with php require func. without any strings to replace, if you just want to use that file as "template" then:
in schema.php:
<?php
echo'<span id="'.$id.'">'.$name.'</span>
<span>'.$imageURL.'</span>';
?>
in class.php:
<?php
class Product {
//logic that is useless to post here.
public function imageURL() {
return "/some/url".$this->id."jpg";
}
}
$imageURL = imageURL(); ?>
Index.php or whatever the main page that handles class.php and temp.php(schema)
<?php
//avoid undefined variables on errors
//in case that you don't check for values submitted
$id = 0;
$name = 0;
$imageURL = '';
//set vars values
$id = /*something*/;
$name = /*something 2*/;
$imageURL = /*something3*/;
//all date will be replaced is ready, oky nothing to wait for
require('path/to/schema.php');
Note: If you gets these data from user, then you should validate with if(isset()).
hope that helps,
I'm new to PHP and I have an issue I can't seem to fix or find a solution to.
I'm trying to create a helper function that will return an 'object' filled with information pulled from an XML file. This helper function, named functions.php contains a getter method which returns a 'class' object filled with data from an SVN log.xml file.
Whenever I try to import this file using include 'functions.php'; none of the code after that line runs the calling function's page is blank.
What am I doing wrong?
Here is what the functions.php helper method and class declaration looks like:
<?php
$list_xml=simplexml_load_file("svn_list.xml");
$log_xml=simplexml_load_file("svn_log.xml");
class Entry{
var $revision;
var $date;
}
function getEntry($date){
$ret = new Entry;
foreach ($log_xml->logentry as $logentry){
if ($logentry->date == $date){
$ret->date = $logentry->date;
$ret->author = $logentry->author;
}
}
return $ret;
}
I'm not sure what the point of having a separate helper function from the class is, personally I'd combine the two. Something like this
other-file.php
require './Entry.php';
$oLogEntry = Entry::create($date, 'svn_log.xml');
echo $oLogEntry->date;
echo $oLogEntry->revision;
Entry.php
class Entry
{
public $revision;
public $date;
public $author;
public static function create($date, $file) {
$ret = new Entry;
$xml = simplexml_load_file($file);
foreach($xml->logentry as $logentry) {
if($logentry->date == $date) {
$ret->date = $logentry->date;
$ret->author = $logentry->author;
$ret->revision = $logentry->revision;
}
}
return $ret;
}
}
EDIT
In light of the fact OP is new to PHP, I'll revise my suggestion completely. How about ditching the class altogether here? There's hardly any reason to use a class I can see at this point; let's take a look at using an array instead.
I might still move the simplexml_load_file into the helper function though. Would need to see other operations to merit keeping it broken out.
entry-helper.php
function getEntry($date, $file) {
$log_xml = simplexml_load_file($file);
$entry = array();
foreach($log_xml->logentry as $logentry) {
if($logentry->date == $date) {
$entry['date'] = $logentry->date;
$entry['author'] = $logentry->author;
$entry['revision'] = $logentry->revision;
}
}
return $entry;
}
other-file.php
require './entry.php';
$aLogEntry = Entry::create($date, 'svn_log.xml');
echo $aLogEntry['date'];
echo $aLogEntry['revision'];
EDIT
One final thought.. Since you're seemingly searching for a point of interest in the log, then copying out portions of that node, why not just search for the match and return that node? Here's what I mean (a return of false indicates there was no log from that date)
function getEntry($date, $file) {
$log_xml = simplexml_load_file($file);
foreach($log_xml->logentry as $logentry) {
if($logentry->date == $date) {
return $logentry;
return false;
}
Also, what happens if you have multiple log entries from the same date? This will only return a single entry for a given date.
I would suggest using XPATH. There you can throw a single, concise XPATH expression at this log XML and get back an array of objects for all the entries from a given date. What you're working on is a good starting point, but once you have the basics, I'd move to XPATH for a clean final solution.
Im wondering if there is a way to autocreate object if a property is called. An example:
<?php
echo $myObj->myProperty
?>
This code will of course fail because i did not initiate $myObj before reading the property.
What im looking for is a way to automaticly initiate $myObj based on "myObj".
Something like:
<?php
class myObj {
public myProperty = 'BlaBla';
}
echo $myObj->myProperty; //outputs BlaBla instead of failing
?>
I know about __autoload($classname) but that only works of initiating classcode with i.e. an include(), so that is not what im after.
You can use magic methods to automate stuff like that...
http://www.php.net/manual/en/language.oop5.magic.php
Just to close this question, this is what i ended up doing:
preg_match_all("/\\\$(.*?)->/si", $code, $matches);
I loop trough the code i get from database looking for any references to objects like
$xxxx->
Then i loop trough the references and create the objects
foreach($matches[1] as $key=>$value) {
$$value = Connector::loadConnector($value);
}
Where the "loadConnector is:
public function loadConnector($connector, $params = NULL) {
require_once $connector. ".php";
$c_name = $connector;
return new $c_name($params);
}
This is of course based on my file structure and it also needs some errorhandling, but so far it looks like it solves my problem :)
BR/Sune
I am trying to assign a variable to a class in PHP, however I am not getting any results?
Can anyone offer any assistance? The code is provided below. I am trying to echo the URL as shown below, by first assigning it to a class variable.
class PageClass {
var $absolute_path = NULL;
function get_absolute_path(){
$url = $this->absolute_path;
echo $url;
}
}
$page = new PageClass();
$page->absolute_path = "http://localhost:8888/smile2/organic/";
$page->get_absolute_path(); //this should echo the URL as defined above - but does not
It also works for me.
Take a look at a live example of your code here.
However, there are a few things you should change about your class.
First, Garvey does make a good point that you should not be using var. That's the older PHP4, less OOP conscious version. Rather declare each variable public or private. In fact, you should declare each function public or private too.
Generally, most classes have private variables, since you usually only want to change the variables in specific ways. To achieve this control you usually set several public methods to allow client functions to interact with your class only in restricted predetermined ways.
If you have a getter, you'd probably want a setter, since these are usually used with private variables, like I described above.
A final note is that functions named get usually return a value. If you want to display a value, it is customary to use a name like display_path or show_path:
<?php
class PageClass
{
private $absolute_path = NULL;
public function set_absolute_path($path)
{
$this->absolute_path = $path;
}
public function display_absolute_path()
{
echo $this->absolute_path;
}
}
$page = new PageClass();
$page->set_absolute_path("http://localhost:8888/smile2/organic/");
$page->display_absolute_path();
// The above outputs: http://localhost:8888/smile2/organic/
// Your variable is now safe from meddling.
// This:
// echo $this->absolute_path;
// Will not work. It will create an error like:
// Fatal error: Cannot access private property PageClass::$absolute_path on ...
?>
Live Example Here
There's a section on classes and objects in the online PHP reference.
class PageClass {
public $absolute_path = NULL;
function get_absolute_path(){
$url = $this->absolute_path;
return $url;
}
}
$page = new PageClass();
$page->absolute_path = "http://localhost:8888/smile2/organic/";
echo $page->get_absolute_path();
Works fine for me.
Have you checked that the script and esp. the code in question is executed at all?
E.g. add some unconditional debug-output to the script. Or install a debugger like XDebug to step through the code and inspect variables.
<?php
class PageClass {
var $absolute_path = NULL; // old php4 declaration, see http://docs.php.net/oop5
function get_absolute_path() { // again old php4 declaration
$url = $this->absolute_path;
echo "debug: "; var_dump($url);
echo $url;
}
}
$page = new PageClass();
$page->absolute_path = "http://localhost:8888/smile2/organic/";
echo "debug: page->get_absolute_path\n";
$page->get_absolute_path();
Hi i've got a problem evaluating json. My goal is to insert json member value to a function variable, take a look at this
function func_load_session(svar){
var id = '';
$.getJSON('data/session.php?load='+svar, function(json){
eval('id = json.'+svar);
});
return id;
}
this code i load session from php file that i've store beforehand. i store that session variable using dynamic var.
<?php
/*
* format ?var=[nama_var]&val=[nilai_nama_var]
*/
$var = $_GET['var'];
$val = $_GET['val'];
$load = $_GET['load'];
session_start();
if($var){
$_SESSION["$var"] = $val;
echo "Store SESSION[\"$var\"] = '".$_SESSION["$var"]."'";
}else if($load){
echo $_SESSION["$load"];
}
?>
using firebug, i get expected response but i also received error
> uncaught exception: Syntax error, unrecognized expression: )
pointing at this
> eval('id = json.'+svar);
I wonder how to solve this
The correct code to use is:
id = json[svar];
You may also want to add alert(svar); to check that svar contains the correct value beforehand.
However, your code still won't work: the func_load_session function will return immediately, before the ajax call finishes and before the id variable is assigned.
what you need to do instead is to perform whatever you want to do with id from the ajax callback function:
function func_load_session(svar){
$.getJSON('data/session.php?load='+svar, function(json){
var id = json[svar];
doSomethingWith(id);
});
}
Also If I understand and have full part of your code Your json comes out like Store["var"]="var" ??
Does not appear valid json
I suggest using php function json_encode()
So php would be
$var = $_GET['var'];
$val = $_GET['val'];
$load = $_GET['load'];
session_start();
if($var){
$_SESSION["$var"] = $val;
echo json_encode(array($var=>$_SESSION[$var])); // or something like that
}else if($load){
echo json_encode(array('load'=>$_SESSION["$load"]);
}
?>