【问题标题】:Load XML in php在 php 中加载 XML
【发布时间】:2012-06-24 21:40:12
【问题描述】:

我有一个 SimpleXMLElement 对象,我想用 PHP 导入。 但它只循环通过 XML 文件中的第一行。 我还想用 $item->columm1 显示特定的列,而不是用它的所有值显示整行。

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

foreach($sxml->Departure->attributes() as $item)
{
    echo $item;
}

编辑:这是输出,请注意我已经使用 text1、text2 编辑了原始值。

SimpleXMLElement Object ( 
[Departure] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => text1 [type] => text2 [stop] => text3 [time] => text4 [date] => text4 [direction] => text5 )

EDIT2:输出->

object(SimpleXMLElement)#4 (2) { ["@attributes"]=> array(6) { ["name"]=> string(6)     "text1" ["type"]=> string(3) "text2" ["stop"]=> string(12) "text3" ["time"]=> string(5) "text4" ["date"]=> string(8) "text5" ["direction"]=> string(10) "text6" } ["JourneyDetailRef"]=> object(SimpleXMLElement)#5 (1) { ["@attributes"]=> array(1) { ["ref"]=> string(125) "text7" } } } 

EDIT3:输出->

  object(SimpleXMLElement)#7 (1) { [0]=> string(6) "text1" } object(SimpleXMLElement)#8 (1) { [0]=> string(3) "text2" } object(SimpleXMLElement)#7 (1) { [0]=> string(12) "text3" } object(SimpleXMLElement)#8 (1) { [0]=> string(5) "text4" } object(SimpleXMLElement)#7 (1) { [0]=> string(8) "text5" } object(SimpleXMLElement)#8 (1) { [0]=> string(10) "text6" } 

【问题讨论】:

    标签: php xml dom foreach


    【解决方案1】:

    $item 已成为对象。当您想要循环播放该项目时,请确保告诉您要在屏幕上回显该项目的哪一部分。

    例如:

    $url = 'file.xml';
    $sxml = simplexml_load_file($url);
    
    //foreach loop
    foreach($sxml->Departure as $item){
        //vardump
        var_dump($item);
    
        //construct next piece of code
        foreach($item->attributes() as $key => $piece){
             echo $key.' = '.$piece;
        }
    }
    

    【讨论】:

    • 你有 XML 数据的例子吗?
    • @user1273409 尝试运行print_r($sxml);var_export($sxml); 并查看对象的结构。从那里你应该能够辨别出可调用的函数。另一种选择可能是在foreach 中执行此操作:die(var_export($item, true));。这将停止执行并打印$item 的结构。从那里,您应该能够看到$item 是什么,并确定您是否在 XML 层次结构中的正确位置以及调用什么。
    • @Tim 我已经在顶部添加了输出。
    • 你试过调试foreach循环的每一步,这样你就可以看到输出了吗?我在答案中举了一个例子。
    • 看起来更好。但是是否可以只显示一个带有变量的属性。所以我可以改变它们的顺序。 $piece->name and $piece->type like mysql with $row
    猜你喜欢
    • 2012-08-19
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2012-03-27
    • 2015-01-09
    相关资源
    最近更新 更多