开发者

Isolate a single item from XML feed with PHP

开发者 https://www.devze.com 2022-12-22 04:30 出处:网络
Hi and thanks for looking. I\'m trying to get just the value in brackets after 1 GBP = USD fro开发者_运维知识库m the following link, how do I do this with SimpleXML?

Hi and thanks for looking.

I'm trying to get just the value in brackets after 1 GBP = USD fro开发者_运维知识库m 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";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消