当前位置: 动力学知识库 > 问答 > 编程问答 >

php - I need to extract a value of the result of xml generated by http query

问题描述:

I could really do with some help with this one, it's driving me mad!

I need to extract the value from an xml file that is generated by an http query...

I will explain...

I need to add a variable to this line:

http://ws.audioscrobbler.com/2.0/?method=artist.search&artist=ADD_ARTIST_HERE&api_key=b25b959554ed76058ac220b7b2e0a026

Which I can do with some variable editing in php

This will generate an xml file which looks like this:

 <lfm status="ok">

<results for="rihanna">

<opensearch:Query role="request" searchTerms="rihanna" startPage="1"/>

<opensearch:totalResults>3821</opensearch:totalResults>

<opensearch:startIndex>0</opensearch:startIndex>

<opensearch:itemsPerPage>30</opensearch:itemsPerPage>

<artistmatches><artist><name>Rihanna</name>

<listeners>3236233</listeners>

<mbid>73e5e69d-3554-40d8-8516-00cb38737a1c</mbid>

<url>http://www.last.fm/music/Rihanna</url>

<streamable>1</streamable>

<image size="small">http://userserve-ak.last.fm/serve/34/71057304.png</image>

<image size="medium">http://userserve-ak.last.fm/serve/64/71057304.png</image>

<image size="large">http://userserve-ak.last.fm/serve/126/71057304.png</image>

<image size="extralarge">http://userserve-ak.last.fm/serve/252/71057304.png</image>

And so the file goes on...

From this xml output generated from my original query, I need to extract the URL in <image size="medium" and put it into another variable...

Sorry for a basic question (or what may be a long answer) but I really don't know how to go about this one at all...

Thank you in advance for any help you may be able to provide me with.

网友答案:

You can have a look at the XPATH function in php to reach that particular image link... the php docs are sufficient to help you out...

网友答案:

Assuming you have the XML string in $str:

$xmlObj = simplexml_load_string($str);    

foreach($xmlObj->results as $result)
{
    foreach($result->artistmatches->artist as $artist)
    {
        foreach($artist->image as $image)
        {
            if($image->attributes()->size == 'medium')
            {
                echo 'size medium: ' . (string)$image;
            }
        }
    }
}

Instead of loading the string you could grab the XML directly from the URL with simplexml_load_file().

网友答案:

I use the Last.fm feed for an app I made and to get the images I used:

$imagexml = simplexml_load_file($imageurl) or $error = "Feed Not Loading";
$album = $imagexml->album;
$image = (string) $album->image[2];

$imageurl being the url for Last.FM and the $image will give you the url of that image

分享给朋友:
您可能感兴趣的文章:
随机阅读: