来自字符串的简单XML - 缺少什么?

时间:2011-08-21 02:57:49

标签: php xml simplexml

我在这里疯狂,我几乎肯定我至少在正确的轨道上。

我只是试图解析我从XML中返回的API获取的响应。我真的只需要打印“Lyric”索引。

Anywho,这是代码:

<?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);
        $result = 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>

这是xml ....

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

2 个答案:

答案 0 :(得分:1)

尝试:

<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>

答案 1 :(得分:1)

您不需要使用foreach,因为只有一首歌词。

你只需要:

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