如何使用PHP在这个xml中读取这个属性?

时间:2017-01-02 06:51:59

标签: php

http://idragonlk.com/channels.xml

这是xml。

想要的是循环阅读这个频道和节目。

<?php 
$xmlDoc = new DOMDocument();
$xmlDoc->load("channels.xml");

$xmlObject = $xmlDoc->getElementsByTagName('channel');
$itemCount = $xmlObject->length;

for ($i=0; $i < $itemCount; $i++){
    $title = $xmlObject->item($i)->getElementsByTagName('display-name')->item(0)->childNodes->item(0)->nodeValue;
    print "Finished Item $title n<br/>";
}
?>

我试过这个。但它打印txt值。我无法获得属性值。

想获得

的价值

频道ID =''

lang =''显示名称

icon src =''value

程序开始=''值

程序停止=''值

program channel =''value

程序评级值

Plz有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

试试这个,也许对你有帮助。

<?php

/*CURL PHP library to get file contents*/
$ch = curl_init();  
curl_setopt($ch, CURLOPT_URL, "http://idragonlk.com/channels.xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
/*End*/

/*Takes a well-formed XML string and returns it as an object.*/
$XMLOutPut = simplexml_load_string($output);


//$channel_list = getChannel_list($XMLOutPut);
//$programme_list = getProgramme_list($XMLOutPut);

echo "<pre>";print_r(getChannel_list($XMLOutPut));
echo "<pre>";print_r(getProgramme_list($XMLOutPut));
exit;

/*Function to fetch channel and programme*/

//channel
function getChannel_list($mainObj){$Result_List =  array();
    for($i=0;$i<count($mainObj->channel);$i++){
        $Result_List[] = objectToArray($mainObj->channel[$i]);
    }
    return $Result_List;
}

//programme
function getProgramme_list($mainObj){$Result_List =  array();
    for($i=0;$i<count($mainObj->programme);$i++){
        $Result_List[] = objectToArray($mainObj->programme[$i]);
    }
    return $Result_List;
}

//Convert Object to array.
function objectToArray($obj) {
    if (is_object($obj)) {$obj = get_object_vars($obj);}

    if (is_array($obj)) {return array_map(__FUNCTION__, $obj);}
        else {return $obj;}
}
?>

<强>输出

Array
(
    [0] => Array
        (
            [@attributes] => Array
                (
                    [id] => 4seven UK
                )

            [display-name] => 4seven UK
            [icon] => Array
                (
                    [@attributes] => Array
                        (
                            [src] => 4seven UK.png
                        )

                )

            [url] => http://www.tvguide.co.uk
        )

    [1] => Array
        (
            [@attributes] => Array
                (
                    [id] => 5STAR UK
                )

            [display-name] => 5STAR UK
            [icon] => Array
            ......
            ......