将 XML 内容转换为 PHP 变量


XML content into PHP variables

我已经在这里待了几个小时了,真的无法让它工作......我在 xml 文件中有以下内容:

<stores data="4850" times="01010101">
  <folder info="storage" DateTime="datetime1" update="212121012" versionNumber="ver1" url="http://url1" locater="location1"/>
  <folder info="images" DateTime="datetime2" update="1421748774" versionNumber="ver2" url="http://url2" locater="location2"/>
</stores data>

我需要使用 PHP 将每个元素放入不同的变量中。这是我拥有的代码,它获取 xml 文件并将其打印出来,但在此之后我卡住了。

$xml_ip = simplexml_load_file('file.xml');
print_r($xml_ip);

有了这个,我得到了屏幕上看起来像一个数组的东西,但我无法将所有 xml 条目都放入变量中。

谢谢。

这不是有效的 XML,如果你使 XML 有效,它将起作用

因此,将文件更改为

<stores data="4850" times="01010101">
  <folder info="storage" DateTime="datetime1" update="212121012" versionNumber="ver1" url="http://url1" locater="location1"/>
  <folder info="images" DateTime="datetime2" update="1421748774" versionNumber="ver2" url="http://url2" locater="location2"/>
</stores>

我所做的只是修复这条线

</stores data>

复制/粘贴每次都会得到你!!

然后你会得到这个:-

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [data] => 4850
            [times] => 01010101
        )
    [folder] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [info] => storage
                            [DateTime] => datetime1
                            [update] => 212121012
                            [versionNumber] => ver1
                            [url] => http://url1
                            [locater] => location1
                        )
                )
            [1] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [info] => images
                            [DateTime] => datetime2
                            [update] => 1421748774
                            [versionNumber] => ver2
                            [url] => http://url2
                            [locater] => location2
                        )
                )
        )
)

回复其他评论

你已经在变量中有这些数据,这一行

$xml_ip = simplexml_load_file('file.xml');

创建一个名为 $xml_ip 的 PHP SimpleXMLElement 对象

你现在需要学习如何处理这个对象,这是文档

这里有一段简单的代码来打印数据作为领先优势。

$xml_ip = simplexml_load_file('file.xml');
echo $xml_ip->attributes()['data'] . PHP_EOL;
echo $xml_ip->attributes()['times'] . PHP_EOL;
foreach ( $xml_ip->folder as $xmlEltObj ) {
    foreach ($xmlEltObj->attributes() as $attr => $val) {
        echo '   '. $attr . " = " . $val.PHP_EOL;
    }
}

哪些打印

4850
01010101
   info = storage
   DateTime = datetime1
   update = 212121012
   versionNumber = ver1
   url = http://url1
   locater = location1
   info = images
   DateTime = datetime2
   update = 1421748774
   versionNumber = ver2
   url = http://url2
   locater = location2