Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Simple calculation script using XML data

1. ## Simple calculation script using XML data

Thank you so much for stopping in on my first thread here. If you know javascript I imagine this will be very simple for you and may only require a line or two of code(I certainly hope). I have spent hours researching how to code this myself and feel confident javascript is the way to go but after several tutorials and videos I still do not understand how to pull XML data from an external site for use in a calculation on my own site. I would gladly buy you a beer(\$5 via paypal) if you are the first person that provides a solution.

LET ME EXPLAIN

Quite simply, I am attempting to use XML data from http://www.xmlcharts.com/cache/industrial-metals.php to calculate a value on my website.

All I want to display is the scrap value of one aluminum can. I need to multiply the XML data for the latest spot of aluminum/lb against .029982.

Thanks again for any help

• As much as I love Beer
I must say to you that
browser security, (same
origin policy) will prevent
you from doing this in a
simple manner.
You could do this using
your server to get the data
then appending that to
the page.

http://en.wikipedia.org/wiki/Same-origin_policy

• Welcome to the forums infinitenothing. My daughter lived in Lancaster, PA. worked at Donnelley's. Working with xml is all ways easier in PHP. Would have given the entire answer in PHP, but kept getting wrong answer in the multiplication so did use JS to do the math and display results.
PHP Code:
``` <?php\$xml=simplexml_load_file("http://www.xmlcharts.com/cache/industrial-metals.php");\$i = 0;foreach (\$xml as \$currency[]){    if (\$currency[\$i]->attributes()->access == "zar"){        if(\$currency[\$i]->price->attributes()->access == "aluminum"){            \$first = \$currency[\$i]->price;            echo \$currency[\$i]->price;  //  So you see what we're working with        }    }    \$i++;}?><script type="text/javascript">    var first = <?php echo \$first; ?>;    var next = .029982;    alert(first*next);   // Don't use alert in your final page use a div.</script> ```
When you said
for the latest spot of aluminum
I took it to mean <currency access="zar"> If not just change the zar.

• one easy and simple method is to use YQL:

Code:
```<script>function yqlCB(data){
.filter(function(price){return price.currency.access=='usd'})[0].currency.price
.filter(function(price){return price.access=='aluminum'})[0].content ) * 0.029982 );
}
</script>
<script src="http://query.yahooapis.com/v1/public/yql?q=select%20currency%20%20from%20xml%20where%20url%3D'http%3A%2F%2Fwww.xmlcharts.com%2Fcache%2Findustrial-metals.php'&format=json&callback=yqlCB"></script>```

• ## Users who have thanked rnd me for this post:

infinitenothing (01-05-2014)

• Wow! Thanks so much sunfighter and rnd_me for the help. Now let me display the limit to my knowledge of both codes mentioned.

Sunfighter, your coding seems to be exactly the kind of direction I need. Only problem is I do not know how to make use of the coding. Apparently I cannot plug this right in html(html&css are pretty much the limit of my coding experience). My best guess is that I create a separate php file. Any clues you could offer? That's neat about your daughter though. My brother-in-law works there now. Great company

Rnd_me, your script provides a calculated total as a popin on my screen. I have learned a little about document.write. Would I add this into the script you provided to produce a written result for my visitor?

BTW, I owe you both a beer either way, pm me so I can paypal you both. To anyone else offering replies to this question, these are the only two beers I am buying for this solution.

• The point--and solution by Sunfighter--is that you can *NOT* access a FILE on another server (domain, actually!) via JavaScript. So he is using PHP code to get the file contents, processes the XML in PHP, and then just dumps data into the HTML/JavaScript code.

Another alternative to this is to use a "proxy server". That would be a very small PHP page you would run on your server that would go grab the contents from the "foreign" domain and serve them up AS IS so that they appear to be coming from your own domain.

Finally, NEVER NEVER NEVER USE DOCUMENT.WRITE! Treat it as poison.

Rnd_Me's script uses the YQL processor and TELLS that processor what to do with the data. To wit:`&format=json&callback=yqlCB`

That is, you are telling YQL to return the results in JSON format and, when the data is ready, to call the function yqlCB. (You could use any name you want there, in place of yqlCB.) RndMe's use of alert( ) is only for illustrative purposes. You would normally, instead, use DOM methods to put the resultant value in place on your page. You can *NOT* use document.write() to do so.

• You all are so extremely helpful. Thanks for saving me so many future hours of brain racking search.

• you can replace my "alert" with "document.getElementById('outputdiv').innerHTML=", where outputdiv is the id of the element you want to contain the Al price for one can.

with yql you get safety and simplicity in one go, but you probably get more flexibility doing it yourself in php and assuming the security responsibility yourself.

• I found what I was doing wrong with the multiplication. You can do the whole thing without JS. Make your .html file into a .php file:
Code:
```<?php
\$i = 0;
foreach (\$xml as \$currency[]){
if (\$currency[\$i]->attributes()->access == "zar"){
if(\$currency[\$i]->price->attributes()->access == "aluminum"){
\$first = \$currency[\$i]->price;
\$alum_price = (float)\$first * .029982;
}
}
\$i++;
}
?>

<!DOCTYPE html>
<html>
<title>Title of the document</title>

<body>
<div id="outputdiv"><?php echo \$alum_price; ?></div>
</body>
</html>```

• ## Users who have thanked sunfighter for this post:

infinitenothing (01-05-2014)

• Okay, despite everyone being so helpful I am lost in how to use either code on my site properly. It is a mediawiki php site similar to wordpress. The javascript produced the alert so I changed it to
Code:
```<script>function yqlCB(data){
document.getElementById("outputdiv").innerHTML=( Number( data.query.results.prices
.filter(function(price){return price.currency.access=='usd'})[0].currency.price
.filter(function(price){return price.access=='aluminum'})[0].content ) * 0.029982 );
}
</script>
<script src="http://query.yahooapis.com/v1/public/yql?q=select%20currency%20%20from%20xml%20where%20url%3D'http%3A%2F%2Fwww.xmlcharts.com%2Fcache%2Findustrial-metals.php'&format=json&callback=yqlCB"></script>

<div id="outputdiv"></div>```
I am also still clueless how to use the php html combo on my site. Please keep in mind the only coding I am versed in is html. I apologize for taking so much of everyone's time and have spent several more hours trying to figure this out myself so I could avoid doing so. Much coffee and many cigarettes later and I am still lost. Even a link to something that might guide me through this would be appreciated.

• put the output div above the script tag - that way the code will know where to put the results when they come in.

• Thanks so much xelawho. That solved that problem.

• Originally Posted by infinitenothing
Thanks so much xelawho. That solved that problem.
yay. it's nice to get something working after a long time. Sounds like you need to paypal yourself a beer or two after all that! glad you got something working...

• So now I am in the process of learning javascript that way I do not have so many questions. I would like to limit the resulting number to two decimals and add a "\$" sign to the final output. Again, the code I'm starting with is
Code:
```<script>function yqlCB(data){
document.getElementById("outputdiv").innerHTML=( Number( data.query.results.prices
.filter(function(price){return price.currency.access=='usd'})[0].currency.price
.filter(function(price){return price.access=='aluminum'})[0].content ) * 0.029982 );
}
</script>
<script src="http://query.yahooapis.com/v1/public/yql?q=select%20currency%20%20from%20xml%20where%20url%3D'http%3A%2F%2Fwww.xmlcharts.com%2Fcache%2Findustrial-metals.php'&format=json&callback=yqlCB"></script>

<div id="outputdiv"></div>```
My best guess based on what I have learned is something like
Code:
```yqlCB = ("\$" + yqlCB);
yglCB = yqlCB.toFixed(2);```
Admittedly I still have not learned how the function above works exactly so I am not sure what variable, if any I would assign this to, or where I would put the coding I am attempting to add.

• Code:
```<div id="outputdiv"></div>

<script type = "text/javascript">

function yqlCB(data) {
var result =( Number( data.query.results.prices
.filter(function(price){return price.currency.access=='usd'})[0].currency.price
.filter(function(price){return price.access=='aluminum'})[0].content ) * 0.029982 );
result = result.toFixed(2);  // makes the value a string with 2 dp
result = "\$" + result;  // prepend the \$ sign
document.getElementById("outputdiv").innerHTML=result;
}

</script>```

• ## Users who have thanked Philip M for this post:

infinitenothing (01-05-2014)

•