simple xml read foreach - php

Wonder if you can help for Christmas.
I am trying to read an XML but am having a few issues, basically the foreach structure isnt letting me return the data in the structure I want, and I am not sure of the correct way of doing this. Example below:
`<event id="298640100" date="Sat Dec 31 16:00:00 CET 2011">
<market id="9064667" type="1" status="Open" period="FT">
<description>Match Betting</description>
<place_terms>Win only</place_terms>
−
<outcome id="6798861400">
<description>Draw</description>
−
<price id="24532283602">
<decimal>3.5</decimal>
<fractional>5/2</fractional>
</price>
<position>2</position>
</outcome>
−
<outcome id="6798861200">
<description>Bolton Wanderers</description>
−
<price id="24532283402">
<decimal>2.0</decimal>
<fractional>1/1</fractional>
</price>
<position>1</position>
</outcome>
−
<outcome id="6798861300">
<description>Wolves</description>
−
<price id="24532283502">
<decimal>3.6</decimal>
<fractional>13/5</fractional>
</price>
<position>3</position>
</outcome>
</market>
</event>`
PHP
`<?php
$source = file_get_contents("vc.xml");
$xml = simplexml_load_string($source);
$game = $xml->xpath("//event");
foreach ($game as $event)
{
echo "<b>Event ID:</b> " . $event['id'] . "<br />";
echo "<b>Event Date:</b> " . $event['date'] . "<br />";
{
foreach ($event->children() as $market)
{
if ($market['period'] == 'FT')
{
foreach ($market->children() as $outcome)
{
echo "<b>Outcome ID:</b> " . $outcome['id'] . "<br />";
foreach ($outcome->children() as $price)
{
echo "<b>Price ID:</b> " . $price ['id'] . "<br />";
foreach ($price->children() as $value)
{
echo "<b>Value:</b> " . $value . "<br />";
}
}
}
}
}
}
echo "<br />";
}
?>`
This is basically returning this:
Event ID: 298640100
Event Date: Sat Dec 31 16:00:00 CET 2011
Outcome ID:
Outcome ID:
Outcome ID: 6798861400
Price ID:
Price ID: 24532283602
Value: 3.5
Value: 5/2
Price ID:
Outcome ID: 6798861200
Price ID:
Price ID: 24532283402
Value: 2.0
Value: 1/1
Price ID:
Outcome ID: 6798861300
Price ID:
Price ID: 24532283502
Value: 3.6
Value: 13/5
Price ID:
Ideally I just want to return the following:
Event ID: 298640100
Event Date: Sat Dec 31 16:00:00 CET 2011
Outcome ID: 6798861400
Price ID: 24532283602
Value: 5/2
Any ideas what I am doing wrong and how I could achieve this.
Thanks in advance
Richard

You have 2 problems here. First, you are using the children() function, which returns all children, not just the specific type you want. This is why you get Outcome ID: 3 times in the begining. Instead of foreach ($market->children() as $outcome) you should use foreach ($market->outcome as $outcome).
Second, it seems like you only want the first result. In that case, you shouldn't be using a foreach. the simplexml object is a set of arrays, and you can access an inividual object in the array by its index number. You can get rid of a lot of your code and just grab the first outcome object directly like this:
$xml->event->market->outcome[0]
You might want to read the official simpleXML documentation http://www.php.net/manual/en/simplexml.examples-basic.php

Here is what i think you need:
foreach ($game as $event)
{
echo "<b>Event ID:</b> " . $event['id'] . "<br />";
echo "<b>Event Date:</b> " . $event['date'] . "<br />";
{
foreach ($event->children() as $market)
{
if ($market['period'] == 'FT')
{
foreach ($market->children() as $name => $outcome )
{
if ( $name != "outcome" )
{
continue;
}
echo "<b>Outcome ID: - $name</b> " . $outcome['id'] . "<br />";
foreach ($outcome->children() as $name => $price)
{
if ( $name != "price" )
{
continue;
}
echo "<b>Price ID:</b> " . $price ['id'] . "<br />";
foreach ($price->children() as $name => $value)
{
if ( $name != "fractional" )
{
continue;
}
echo "<b>Value: - $name</b> " . $value . "<br />";
break;
}
}
break;
}
break;
}
}
}
echo "<br />";
}

Related

PHP get data form XML using PHPSimpleXML

I am trying to get data from an xml file and am having trouble as the table has a bit more levels than the examples I can find.
I want to be able to iterate through each instance of <Event> as <Information> and <Events> only open and close the data. The <Event> repeats based on the number of events logged.
A sample of the table structure is:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Information>
<Events>
<Event>
<Time>3141.29</Time>
<PrimaryObject ID="487">
<Name>Player1</Name>
<Country>us</Country>
</PrimaryObject>
<Action>Move</Action>
<SecondaryObject ID="814">
<Name>Dog</Name>
<Parent>487</Parent>
</SecondaryObject>
</Event>
</Events>
</Information>
The PHP code is:
<!DOCTYPE html>
<html>
<body>
<?php
$xml=simplexml_load_file("data.xml") or die("Error: Cannot create object");
foreach($xml->Event as $events) {
$id = $events->PrimaryObject->attributes();
$name = $events->PrimaryObject->Name;
...
echo $id['ID'].' '. $name;
echo "<br>";
}
?>
</body>
</html>
You have to use the Events
$xml->Events->Event as $events
For example
$xml=simplexml_load_file("data.xml") or die("Error: Cannot create object");
foreach($xml->Events->Event as $events) {
$id = $events->PrimaryObject->attributes();
$name = $events->PrimaryObject->Name;
echo $id['ID'].' '. $name;
echo "<br>";
}
Output
487 Player1
Php demo
I'm not sure what data exactly you are looking for, but here's everything, using xpath, and you can pick and choose:
$events = $xml->xpath('.//Event');
foreach($events as $event) {
$dat = $event->xpath('./PrimaryObject')[0];
$time= $event->xpath('./Time');
$id = $dat->xpath('./#ID');
$name = $dat->xpath('./Name');
$country = $dat->xpath('./Country');
$dat2 = $event->xpath('./SecondaryObject')[0];
$action= $event->xpath('./Action');
$id2 = $dat2->xpath('./#ID');
$name2 = $dat2->xpath('./Name');
$parent = $dat2->xpath('./Parent');
echo 'Time: ' . $time[0];
echo "<br>";
echo 'Action: ' . $action[0];
echo "<br>";
echo "<br>";
echo 'Primary Object Data:';
echo "<br>";
echo 'ID: ' . $id[0];
echo "<br>";
echo 'Name: ' . $name[0];
echo "<br>";
echo 'Country: ' . $country[0];
echo "<br>";
echo "<br>";
echo "<br>";
echo 'Secondary Object Data:';
echo "<br>";
echo 'ID: ' . $id2[0];
echo "<br>";
echo 'Name: ' . $name2[0];
echo "<br>";
echo 'Parent: ' . $parent[0];
echo "<br>";
}
Output:
Time: 3141.29
Action: Move
Primary Object Data:
ID: 487
Name: Player1
Country: us
Secondary Object Data:
ID: 814
Name: Dog
Parent: 487

Php - Showing youtube videos in a table

I'm working with the youtube v3 api. After a few tests, I realized that I need some help. When I'm trying to display the xml content, I'm just getting null values. Can anybody help me?
If you want to see the xml:
https://www.youtube.com/feeds/videos.xml?channel_id=$channelid
And my code is:
$xml=simplexml_load_file("videos.xml");
foreach($xml as $content) {
echo $content->title . "<br>";
echo $content->link['href'] . "<br>";
}
Xml that I want to display:
<entry>
Video ID <yt:videoId>Q4vSZA_8kYY</yt:videoId>
Video title <title>¡Trailer del canal! CBPrductions</title>
Upload date <published>2016-01-14T07:37:03+00:00</published>
<media:group>
Description <media:description>
LIKE PORQUE LO DIGO YO _ Suscribete!: https://www.youtube.com/user/SpanishCBProductions Dale a LIKE a mi página Facebook: https://www.facebook.com/SpanishCBProductions Sigueme en TWITTER!: https://twitter.com/CcristianN3 Y en mi poco sexy INSTAGRAM: http://instagram.com/ccristiann3/
</media:description>
</media:group>
</entry>
I think you can register the namespace and use xpath.
Then for the 'media' and the 'yt' you can get the children by passing the namespace.
If you want to display the first entry:
$url = 'https://www.youtube.com/feeds/videos.xml?channel_id=UCRGn72Qu0KTtI_ujNxRr3Fg';
$xml = simplexml_load_file($url);
$ns = $xml->getDocNamespaces(true);
$xml->registerXPathNamespace('a', 'http://www.w3.org/2005/Atom');
$elements = $xml->xpath('//a:entry');
$content = $elements[0];
$yt = $content->children('http://www.youtube.com/xml/schemas/2015');
$media = $content->children('http://search.yahoo.com/mrss/');
echo "Video ID: " . $yt->videoId . "<br>";
echo "Video title: " . $content->title . "<br>";
echo "Upload date: " . $content->published . "<br>";
echo "Description: " .$media->group->description . "<br>";
If you want to display the information from all the entries, you can use:
foreach ($elements as $content) {
$yt = $content->children('http://www.youtube.com/xml/schemas/2015');
$media = $content->children('http://search.yahoo.com/mrss/');
echo "Video ID: " . $yt->videoId . "<br>";
echo "Video title: " . $content->title . "<br>";
echo "Upload date: " . $content->published . "<br>";
echo "Description: " . $media->group->description . "<br>";
echo "<br>";
}

Iterating through XML with SimpleXML and XPath, Result is in wrong order

my variables.php
$xmlFile = 'xml.xml';
$xmlFileLoad = simplexml_load_file($xmlFile);
$xmlFileLoad->registerXPathNamespace("oi", "http://www.openimmo.de");
$immobilie = $xmlFileLoad->xpath('//oi:immobilie');
$zustand_angaben_letztemodernisierung = $xmlFileLoad->xpath('/oi:openimmo/oi:immobilie/oi:zustand_angaben/oi:letztemodernisierung');
$zustand_angaben_zustand = $xmlFileLoad->xpath('/oi:openimmo/oi:immobilie/oi:zustand_angaben/oi:zustand/#zustand_art');
$zustand_angaben_alter = $xmlFileLoad->xpath('/oi:openimmo/oi:immobilie/oi:zustand_angaben/oi:alter/#alter_attr');
$zustand_angaben_erschliessung = $xmlFileLoad->xpath('/oi:openimmo/oi:immobilie/oi:zustand_angaben/oi:erschliessung/#erschl_attr');
$zustand_angaben_altlasten = $xmlFileLoad->xpath('/oi:openimmo/oi:immobilie/oi:zustand_angaben/oi:altlasten');
$zustand_angaben_baujahr = $xmlFileLoad->xpath('/oi:openimmo/oi:immobilie/oi:zustand_angaben/oi:baujahr');
the xml file (shorted version)
<?xml version="1.0" encoding="utf-8"?>
<openimmo xmlns="http://www.openimmo.de"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.openimmo.de openimmo.xsd">
<immobilie>
<zustand_angaben>
<altlasten>keine</altlasten>
</zustand_angaben>
</immobilie>
<immobilie>
<zustand_angaben>
<altlasten>keine</altlasten>
</zustand_angaben>
</immobilie>
<immobilie>
<zustand_angaben>
<altlasten>keine</altlasten>
</zustand_angaben>
</immobilie>
<immobilie>
<zustand_angaben>
<baujahr>ca. 1900</baujahr>
<altlasten>nein</altlasten>
</zustand_angaben>
</immobilie>
<immobilie>
<zustand_angaben>
<baujahr>ca. 1989</baujahr>
<zustand zustand_art="ERSTBEZUG" />
<alter alter_attr="ALTBAU" />
<altlasten>keine</altlasten>
</zustand_angaben>
</immobilie>
</openimmo>
my show.php
<?php
include("variables.php");
$i = 0;
foreach ($immobilie as $immo) {
echo "Immobilie $i<br />";
if(isset($zustand_angaben_zustand[$i])) {
echo $zustand_angaben_zustand[$i] . "</br>";
}
if(isset($zustand_angaben_alter[$i])) {
echo $zustand_angaben_alter[$i] . "</br>";
}
if(isset($zustand_angaben_erschliessung[$i])) {
echo $zustand_angaben_erschliessung[$i] . "</br>";
}
if(isset($zustand_angaben_altlasten[$i])) {
echo $zustand_angaben_altlasten[$i] . "</br>";
}
if(isset($zustand_angaben_baujahr[$i])) {
echo $zustand_angaben_baujahr[$i] . "</br>";
}
echo "<br /><br />";
$i++;
}
?>
when i'm executing the code, the result will be the following
Immobilie 0
ERSTBEZUG
ALTBAU
keine
5
A
5
A++
ca. 1900
Immobilie 1
keine
ca. 1989
Immobilie 2
keine
Immobilie 3
nein
Immobilie 4
keine
but i want it in the order like in the xml, so Immobilie 0 has only keine, Immobilie 1 and 2 too, the third 1900 and nein and last but not least Immobilie 4 with all the properties in the xml...
what am i doing wrong?
Use XPath expressions that relative to current immobilie element instead :
$i = 0;
foreach ($immobilie as $immo) {
$immo->registerXPathNamespace("oi", "http://www.openimmo.de");
$zustand_angaben_letztemodernisierung = $immo->xpath('./oi:zustand_angaben/oi:letztemodernisierung');
$zustand_angaben_zustand = $immo->xpath('./oi:zustand_angaben/oi:zustand/#zustand_art');
$zustand_angaben_alter = $immo->xpath('./oi:zustand_angaben/oi:alter/#alter_attr');
$zustand_angaben_erschliessung = $immo->xpath('./oi:zustand_angaben/oi:erschliessung/#erschl_attr');
$zustand_angaben_altlasten = $immo->xpath('./oi:zustand_angaben/oi:altlasten');
$zustand_angaben_baujahr = $immo->xpath('./oi:zustand_angaben/oi:baujahr');
echo "Immobilie $i<br />";
if(isset($zustand_angaben_zustand[0])) {
echo $zustand_angaben_zustand[0] . "</br>";
}
if(isset($zustand_angaben_alter[0])) {
echo $zustand_angaben_alter[0] . "</br>";
}
if(isset($zustand_angaben_erschliessung[0])) {
echo $zustand_angaben_erschliessung[0] . "</br>";
}
if(isset($zustand_angaben_altlasten[0])) {
echo $zustand_angaben_altlasten[0] . "</br>";
}
if(isset($zustand_angaben_baujahr[0])) {
echo $zustand_angaben_baujahr[0] . "</br>";
}
echo "<br /><br />";
$i++;
}
eval.in demo
As you run the xpath queries in parallel, they have all their order next to each other.
For your example in specific you yet don't really need xpath, the document looks like the perfect job for SimpleXMLElement, you can retrieve the data directly from it.
If you foreach over the objects you're interested in (here most likely each immobilie element) and then extract the data (filter away unset elements), it can work similar to the following example:
$xml = simplexml_load_string($string);
foreach ($xml->immobilie as $immobilie) {
$angaben = $immobilie->zustand_angaben;
$data = [
'letzte_modernisierung' => $angaben->letztemodernisierung,
'zustand_art' => $angaben->zustand['zustand_art'],
'alter' => $angaben->alter['alter_attr'],
'erschliessung' => $angaben->erschliessung['erschl_attr'],
'altlasten' => $angaben->altlasten,
'baujahr' => $angaben->baujahr,
];
echo " * Immobilie:\n";
foreach(array_filter($data) as $label => $wert) {
echo " - $label: $wert\n";
}
}
The output is (also: online-demo):
* Immobilie:
- altlasten: keine
* Immobilie:
- altlasten: keine
* Immobilie:
- altlasten: keine
* Immobilie:
- altlasten: nein
- baujahr: ca. 1900
* Immobilie:
- zustand_art: ERSTBEZUG
- alter: ALTBAU
- altlasten: keine
- baujahr: ca. 1989
Xpath is not bad at all, for a scenario like you have it here, I would then recommend you to use DOMDocument instead of SimpleXMLElement as it's more flexible with Xpath thanks to the evaluate method DOMXpath has.
In any case, you can further read on with this question that shows one DOMDocument and one SimpleXMLElement based solution for Xpath based data-retrieval from XML documents:
PHP XPath. Convert complex XML to array

How do I return a value from a second function in PHP?

I'm a green green newbie trying to write a simple program in PHP. I use an HTML form to ask a "diner" to select an entree, which sends the choice to a PHP program.The PHP program is supposed to echo the entree choice, suggest a drink to the diner, and then tell the diner what the cost of the entree, drink is--including tax and tip.
The first function select_beverage accepts the choice of entree and echoes out the suggested drink and drink price. It then calls function wallet_buster which calculates the taxed cost of the bill. Wallet_buster() is then supposed to return the taxed cost back to select_beverage() which in turn should return the taxed cost back to the variable that called select_beverage.
I can get a simplified version of this program to work but not this beast. My teacher suggested that I save the value returned from wallet_buster as a variable, which I would then return at the end of the if/else cascade. I've tried to follow that suggestion in this code but it's not working. I've also tried
return wallet_buster($steak_price, $steak_drink_price);
in each if/else function but that's not working either.
Thanks in advance for any enlightenment you can provide!
<?php
echo "<h3>Thank you for dining at Elysium Excelsior</h3><br>";
function wallet_buster($entree_price, $drink_price) {
$taxed_cost = 1.1 * ($entree_price + $drink_price);
echo "<br/>";
return $taxed_cost;
}
function select_beverage($dinner) {
$steak_price = 27.50;
$steak_drink = "Justin Cabernet Sauvignon";
$steak_drink_price = 13.15;
$salmon_price = 24.95;
$salmon_drink = "Russian River Pinot Noir";
$salmon_drink_price = 12.25;
$barbecue_pork_price = 22.99;
$barbecue_pork_drink = "Dogfish Head 120 Minute IPA";
$barbecue_pork_drink_price = 7.99;
$chicken_price = 21.50;
$chicken_drink = "Blue Nun Sauvignon Blanc";
$chicken_drink_price = 12.25;
if ($dinner == "1") {
echo "The filet mignon pairs wonderfully with a glass of " . $steak_drink .
at a price of $" . $steak_drink_price . ".<br/>";
echo "<br/>";
$receipt = wallet_buster($steak_price, $steak_drink_price);
}
else if ($dinner == "2") {
echo "A glass of " . $salmon_drink . " for a luxuriously priced $" .
$salmon_drink_price . " is a wonderful complement to our
salmon."".<br/>";
echo "<br/>";
$receipt = wallet_buster($steak_price, $steak_drink_price);
}
else if ($dinner == "3") {
echo "Try a pint of " . $barbecue_pork_drink . " for only $" .
$barbecue_pork_drink_price . "."".<br/>";
echo "<br/>";
$receipt = wallet_buster($steak_price, $steak_drink_price);
}
else if ($dinner == "4") {
echo "Stiller and Meara invite you to try " . $chicken_drink . " at $" .
$chicken_drink_price . " per glass with the chicken!"".<br/>";
echo "<br/>";
$receipt = wallet_buster($steak_price, $steak_drink_price);
}
else {
echo "Please select an entree from our drop-down menu and we will recommend
a beverage suited to your choice.";
echo "<br/>";
}
return $receipt;
}
$dinner = $_GET["entree"];
$big_deal_meal = select_beverage($dinner);
echo "<br>";
echo "We encourage our patrons to tip well; given your menu selections, we ` `believe your bill should be : $" . (1.25 * $big_deal_meal);
?>
Your code is mostly working, you simply misplaced some quotes and concatenation. Adding quotes where they shouldn't be or forgetting to add them where needed will cause PHP to misinterpret your code. You might consider using a code editor or IDE to avoid this in the future. They will highlight your code to alert you when you make a mistake like missing a quote. An IDE like Netbeans will constantly check your code for syntactical mistakes.
Enabling error reporting in your PHP configuration will also give you useful hints about what is going wrong in your scripts.
Here is the working code:
<?php
echo "<h3>Thank you for dining at Elysium Excelsior</h3><br>";
function wallet_buster($entree_price, $drink_price) {
$taxed_cost = 1.1 * ($entree_price + $drink_price);
echo "<br/>";
return $taxed_cost;
}
function select_beverage($dinner) {
$steak_price = 27.50;
$steak_drink = "Justin Cabernet Sauvignon";
$steak_drink_price = 13.15;
$salmon_price = 24.95;
$salmon_drink = "Russian River Pinot Noir";
$salmon_drink_price = 12.25;
$barbecue_pork_price = 22.99;
$barbecue_pork_drink = "Dogfish Head 120 Minute IPA";
$barbecue_pork_drink_price = 7.99;
$chicken_price = 21.50;
$chicken_drink = "Blue Nun Sauvignon Blanc";
$chicken_drink_price = 12.25;
if ($dinner == "1") {
echo "The filet mignon pairs wonderfully with a glass of " . $steak_drink . "
at a price of $" . $steak_drink_price . ".<br/>";
echo "<br/>";
$receipt = wallet_buster($steak_price, $steak_drink_price);
}
else if ($dinner == "2") {
echo "A glass of " . $salmon_drink . " for a luxuriously priced $" .
$salmon_drink_price . " is a wonderful complement to our salmon <br/>";
echo "<br/>";
$receipt = wallet_buster($steak_price, $steak_drink_price);
}
else if ($dinner == "3") {
echo "Try a pint of " . $barbecue_pork_drink . " for only $" .
$barbecue_pork_drink_price . ". <br/>";
echo "<br/>";
$receipt = wallet_buster($steak_price, $steak_drink_price);
}
else if ($dinner == "4") {
echo "Stiller and Meara invite you to try " . $chicken_drink . " at $" .
$chicken_drink_price . " per glass with the chicken! <br/>";
echo "<br/>";
$receipt = wallet_buster($steak_price, $steak_drink_price);
}
else {
echo "Please select an entree from our drop-down menu and we will recommend
a beverage suited to your choice.";
echo "<br/>";
}
return $receipt;
}
$dinner = $_GET["entree"];
$big_deal_meal = select_beverage($dinner);
echo "<br>";
echo "We encourage our patrons to tip well; given your menu selections, we believe your bill should be : $" . (1.25 * $big_deal_meal);
?>
Also note that you do not need to concatenate (with a '.') the text and html. Only when you're mixing in PHP code like variables.
So this: "<span>" . "I am a string" . "</span><br>"; is unnecessary. This: "<span>I am a string</span><br>"; is just fine and easier to read.
Something like this?
function select_beverage($dinner) {
$steak_price = 27.50;
$steak_drink = "Justin Cabernet Sauvignon";
$steak_drink_price = 13.15;
$salmon_price = 24.95;
$salmon_drink = "Russian River Pinot Noir";
$salmon_drink_price = 12.25;
$barbecue_pork_price = 22.99;
$barbecue_pork_drink = "Dogfish Head 120 Minute IPA";
$barbecue_pork_drink_price = 7.99;
$chicken_price = 21.50;
$chicken_drink = "Blue Nun Sauvignon Blanc";
$chicken_drink_price = 12.25;
$selected_meal_price = NULL;
$selected_drink_price = NULL;
if ($dinner == "1") {
echo "The filet mignon pairs wonderfully with a glass of " . $steak_drink . "at a price of $" . $steak_drink_price . ".<br/>";
echo "<br/>";
$selected_meal_price = $steak_price;
$selected_drink_price = $steak_drink_price;
}
else if ($dinner == "2") {
echo "A glass of " . $salmon_drink . " for a luxuriously priced $" . $salmon_drink_price . " is a wonderful complement to our salmon<br/>";
echo "<br/>";
$selected_meal_price = $salmon_price;
$selected_drink_price = $salmon_drink_price;
}
else if ($dinner == "3") {
echo "Try a pint of " . $barbecue_pork_drink . " for only $" . $barbecue_pork_drink_price . ".<br/>";
echo "<br/>";
$selected_meal_price = $barbecue_pork_price;
$selected_drink_price = $barbecue_pork_drink_price;
}
else if ($dinner == "4") {
echo "Stiller and Meara invite you to try " . $chicken_drink . " at $" . $chicken_drink_price . " per glass with the chicken!.<br/>";
echo "<br/>";
$selected_meal_price = $chicken_price;
$selected_drink_price = $chicken_drink_price;
}
else {
echo "Please select an entree from our drop-down menu and we will recommend a beverage suited to your choice.";
echo "<br/>";
}
if(!is_null($selected_meal_price) && !is_null($selected_drink_price)) {
$receipt = wallet_buster($selected_meal_price, $selected_drink_price);
}
return $receipt;
}
As others have pointed out, you were pretty much there. You may also want to note that if you have a double quoted string (") as opposed to single quoted ('), php will interpret variables within.
$var = 3;
echo "The value of var is $var"; //The value of var is 3
Of course, you also need to remember to escape the $ for when you need the actual dollar sign (\$). You could also look into using sprintf to make your output a bit more clean.
Another useful tip is going into the terminal and running php -l <file> to check for syntax errors.
<?php
echo "<h3>Thank you for dining at Elysium Excelsior</h3><br>";
function wallet_buster($entree_price, $drink_price) {
$taxed_cost = 1.1 * ($entree_price + $drink_price);
echo "<br/>";
return $taxed_cost;
}
function select_beverage($dinner) {
$steak_price = 27.50;
$steak_drink = "Justin Cabernet Sauvignon";
$steak_drink_price = 13.15;
$salmon_price = 24.95;
$salmon_drink = "Russian River Pinot Noir";
$salmon_drink_price = 12.25;
$barbecue_pork_price = 22.99;
$barbecue_pork_drink = "Dogfish Head 120 Minute IPA";
$barbecue_pork_drink_price = 7.99;
$chicken_price = 21.50;
$chicken_drink = "Blue Nun Sauvignon Blanc";
$chicken_drink_price = 12.25;
if ($dinner == "1") {
echo "The filet mignon pairs wonderfully with a glass of $steak_drink at a price of \$ $steak_drink_price .<br/>";
echo "<br/>";
$receipt = wallet_buster($steak_price, $steak_drink_price);
}
else if ($dinner == "2") {
echo "A glass of $salmon_drink for a luxuriously priced \$ $salmon_drink_price is a wonderful complement to our salmon.<br/>";
echo "<br/>";
$receipt = wallet_buster($steak_price, $steak_drink_price);
}
else if ($dinner == "3") {
echo "Try a pint of $barbecue_pork_drink for only \$ $barbecue_pork_drink_price.<br/>";
echo "<br/>";
$receipt = wallet_buster($steak_price, $steak_drink_price);
}
else if ($dinner == "4") {
echo "Stiller and Meara invite you to try $chicken_drink at \$ $chicken_drink_price per glass with the chicken!<br/>";
echo "<br/>";
$receipt = wallet_buster($steak_price, $steak_drink_price);
}
else {
echo "Please select an entree from our drop-down menu and we will recommend a beverage suited to your choice.";
echo "<br/>";
}
return $receipt;
}
$dinner = $_GET["entree"];
$big_deal_meal = select_beverage($dinner);
echo "<br>";
echo "We encourage our patrons to tip well; given your menu selections, we` `believe your bill should be : $" . (1.25 * $big_deal_meal);
?>
Best of luck with the rest of your O'Reilly course.

How to get a value from wunderground .json

I'm working on json source from wunderground.com. As the example code displayed in the document. I can adjust and work out for some simple format. But I'm stuck with this one. I tried to googled every where but there's no solution.
Here's the sample codes:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
?>
Well, I need some information like "Cedar Rapids" out of pws/station :
"pws": {
"station": [
{
"neighborhood":"Ellis Park Time Check",
"city":"Cedar Rapids",
"state":"IA",
"country":"US",
"id":"KIACEDAR22",
"lat":41.981174,
"lon":-91.682632,
"distance_km":2,
"distance_mi":1
}
]
}
(You can get all code by clicking this : http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json )
Now the questions are:
What is this data called? (array, array in array?)
How could I pull this data out of the line?
Regards,
station is an array within the pws object.
To get the data, you can do something like this:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
$stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
$count = count($stations);
for($i = 0; $i < $count; $i++)
{
$station = $stations[$i];
if (strcmp($station->{'id'}, "KIACEDAR22") == 0)
{
echo "Neighborhood: " . $station->{'neighborhood'} . "\n";
echo "City: " . $station->{'city'} . "\n";
echo "State: " . $station->{'state'} . "\n";
echo "Latitude: " . $station->{'lat'} . "\n";
echo "Longitude: " . $station->{'lon'} . "\n";
break;
}
}
?>
Output:
Current temperature in Cedar Rapids is: 38.5
Neighborhood: Ellis Park Time Check
City: Cedar Rapids
State: IA
Latitude: 41.981174
Longitude: -91.682632

Categories