开发者

Simple XML from string - what's missing?

I'm driving myself crazy here, I'm almost positive I am at least on the right track.

I'm just trying to parse a response that I am getting from an API that comes back in XML. I really only need to print the "Lyric" index.

Anywho, here is the code:

<?php
    $artist = $_GET['artist'];
    $song = $_GET['song'];

    if(isset($_GET['artist']) && isset($_GET['song']))
    {
        $result = get_lyrics($artist, $song);
    } else {
        $result = "";
    }

    function get_lyrics($artist, $song)
    {
        $postURL = "http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=".urlencode($artist)."&song=".urlencode($song);
        echo $postURL;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postURL);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        $re开发者_运维问答sult = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

?>


<html>
    <head><title>Lyric Search</title></head>

    <form action="<?=$_SERVER['PHP_SELF']?>" method="get">
        <p>Artist<input type="input" name="artist" /></p>
        <p>Song<input type="input" name="song" /></p>
        <input type="submit" value="submit" />
    </form>

    <div id="results">
        <?php

            $xml = simplexml_load_string($result);

            foreach($xml->GetLyricResult as $lyric)
            {
                echo $lyric->Lyric;
            }
        ?>
    </div>
</html>

And here is the xml....

http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=lady+gaga&song=poker+face


You don't need to use foreach because there's only one lyric.

you just need:

<div id="results">
<?php
$xml = simplexml_load_string($result);
echo $xml->Lyric[0];
?>
</div>


Try:

<html>
    <head><title>Lyric Search</title></head>

    <form action="<?=$_SERVER['PHP_SELF']?>" method="get">
        <p>Artist<input type="input" name="artist" /></p>
        <p>Song<input type="input" name="song" /></p>
        <input type="submit" value="submit" />
    </form>

    <div id="results">
<?php
    if(isset($_GET['artist']) && isset($_GET['song'])){
        $result = get_lyrics($_GET['artist'],$_GET['song']);
        $xml = simplexml_load_string($result);

        echo "<pre>";
        //print_r($xml);
        echo $xml->Lyric;
        echo "</pre>";
    }

    function get_lyrics($artist, $song)
    {
        $postURL = "http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=".urlencode($artist)."&song=".urlencode($song);
        echo $postURL;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postURL);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }
?>
    </div>
</html>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜