Hi and thanks for looking.
I'm trying to get just the value in brackets after 1 GBP = USD from the following link, how do I do this with SimpleXML?
http://www.sloomedia.com/currency/feeds/GBP.xml
Thanks, Ben.
Hi and thanks for looking.
I'm trying to get just the value in brackets after 1 GBP = USD from the following link, how do I do this with SimpleXML?
http://www.sloomedia.com/currency/feeds/GBP.xml
Thanks, Ben.
You can try with xpath :
$xml = new SimpleXMLElement($string);
/* On cherche <item><title> */
$result = $xml->xpath('/item/title');
while(list( , $node) = each($result)) {
$matches = array();
preg_match('/\((.*)\)/', $node, $matches);
//do wathever you need with result
//echo $matches[1];
}
I haven't tested the regexp quickly written, you can find something better or use substr as the length of '1GBP = XXX' is constant in your file
In order to "isolate" (or rather, select) the right node, you can use the XPath function starts-with()
.
After selecting the node, you still have to parse its contents. For that, you can use any kind of string-manipulation function in PHP.
$rss = simplexml_load_file('http://www.sloomedia.com/currency/feeds/GBP.xml');
$nodes = $rss->xpath('//item[starts-with(title, "1 GBP = USD")]');
if (empty($nodes))
{
die('No GBP = USD nodes');
}
// Now you got the right node in $nodes[0], you just have to extract the value in parentheses
// The simple way -- 13 is the number of characters in "1 GBP = USD ("
$usd = substr($nodes[0]->title, 13, -1);
// The flexible way
if (!preg_match('#\\(([0-9]+\\.[0-9]+)\\)#', $nodes[0]->title, $m))
{
die('Could not parse the value');
}
$usd = $m[1];
// If you want to parse every item
foreach ($rss->channel->item as $item)
{
if (!preg_match('#1 ([A-Z]+) = ([A-Z]+) \\(([0-9]+\\.[0-9]+)\\)#', $item->title, $m))
{
echo 'Could not parse ', $item->title, "\n";
continue;
}
echo '1 ', $m[1], ' = ', $m[3], ' ', $m[2], "\n";
}