php的simplexml echo问题

时间:2011-04-30 02:30:16

标签: php xml parsing

我正在尝试使用xml来获取标题和guid。有了下面的鳕鱼,我什么都没有回复给我。

$url = 'file.xml';
$obj = simplexml_load_file($url);

$returnTitle = array();
foreach ($obj->title as $title) {
    $returnTitle[];
}

$returnURL = array();
foreach ($obj->guid as $URL) {
    $returnURL[];
}

echo $returnTitle[0]." : ".$returnURL[0]."\n";
echo $returnTitle[1]." : ".$returnURL[1];

XML文件

[item] => Array
(
    [0] => SimpleXMLElement Object
    (
        [title] => here is some title text
        [link] => 
        [comments] => 
        [pubDate] => Fri, 10 Apr 2011 12:00:15 +0000
        [category] => Array
        (
            [0] => SimpleXMLElement Object()     
            [1] => SimpleXMLElement Object()     
            [2] => SimpleXMLElement Object()     
            [3] => SimpleXMLElement Object()     
            [4] => SimpleXMLElement Object()     
            [5] => SimpleXMLElement Object()     
            [6] => SimpleXMLElement Object()     
            [7] => SimpleXMLElement Object()     
        )     
        [guid] => http://blog.website.com/?p=65421
        [description] => SimpleXMLElement Object()     
    )
)

2 个答案:

答案 0 :(得分:0)

你错过了两个for循环中的赋值操作

foreach ($obj->title as $title) {
    $returnTitle[] = $title;
}

答案 1 :(得分:0)

如果您确实已将某些内容分配给$returnTitle$returnURL ...

,则可能
$returnTitle[] = $title;

看看XML的结构,我想你宁愿做这样的事情:

foreach ($obj->item as $item) {
    $returnTitle[] = $item->title;
}

为什么你要分开我不知道的标题和指导,在我看来它们属于一起,所以你应该把它们放在一起:

$items = array();
foreach ($obj->item as $item) {
    $items[] = array('title' => $item->title, 'url' => $item->guid);
}

var_dump($items);

foreach ($items as $item) {
    echo "$item[title] : $item[url]\n";
}