Hope the title was OK.
My problem is that I want to generate an XML file, which contains all the ISO 4217 currencies, including their name, code and countries they are used in.
To do this I'm using simple_html_dom to grab the HTML, and select specific data from the page. Then using SimpleXML to construct the XML. I would like the output like so:
<currency>
<code>USD</code>
<name>United States Dollars</name>
<location>United States of America</location>
</currency>
At the moment I can populate the code for all the codes, but cannot get the names or locations as well as the codes wrapped in currency
Here is the current code I have, the second for loop returns the names of the currency, but I can't figure out how to place this below the code tag within currency:
<?php
//Source: simplehtmldom.sourceforge.net
require('simple_html_dom.php');
//177 currencies
//set URL to parse
$url = "http://en.wikipedia.org/wiki/ISO_4217";
$html = file_get_html($url);
//find all <td> elements that are nested within <table class="wikitable"><tr> and put them into an array
$content = $html->find('table.wikitable tr td');
$newsXML = new SimpleXMLElement("<currencies></currencies>");
$newsXML->addAttribute('type', 'ISO_4217');
Header('Content-type: text/xml');
//loop to add each currency code in <currency><code>HERE</code></currency>
//this loop gets all the codes of the currencies
for($i = 0; $i <= 885; $i += 5){
$currency = $newsXML->addChild('currency');
$code = $currency->addChild('code',strip_tags($content[$i]));
}
//this loop gets all the names of the currencies
for($n = 3; $n <= 531; $n += 5){
$name = $currency->addChild('name',strip_tags($content[$n]));
}
//echo the XML
echo $newsXML->asXML();
?>
I have only started learning PHP a month or so back, so would appreciate any advice, or a point in the correct direction.
(Hope the开发者_JAVA百科 formatting/title naming convention is OK).
Your problem is that the $currency
in the second loop is static, resulting in something like
<currency>
<code>foo</code>
</currency>
<currency>
<code>bar</code>
</currency>
<currency>
<code>baz</code>
<name>nfoo</name>
<name>nbar</name>
<name>nbaz</name>
</currency>
You need to add both name and code to the same $currency
object.
I never found the answer to this issue, and just ended up echo
'ing the XML rather than constructing it via SimpleHTMLDom.
精彩评论