如何使用simplexml_load_string从XML读取数据

时间:2017-12-20 12:41:20

标签: php arrays xml simplexml

我想从我的XML中显示一些数据。这是我的XML:

[@attributes] => Array (
[id] => 2065 )
[price] => Array (
    [@attributes] => Array (
    [gross] => 1259.16
    [net] => 1023.71
    [vat] => 23.0 )
    )
[srp] => Array (
    [@attributes] => Array (
    [gross] => 1499.00
    [net] => 1218.7
    [vat] => 23.0 )
    )
[sizes] => Array (
    [size] => Array (
        [@attributes] => Array (
        [id] => 0
        [code_producer] => 33124.16.EN
        [code] => 2065-0
        [weight] => 999 )
        [stock] => Array (
            [@attributes] => Array (
            [id] => 1
            [quantity] => 1
            )
        )
    )

我想从中获得价值:

  • [id] => 2065年,
  • [price] [net] => 1023.71,
  • [尺寸] [尺寸] [库存] [数量] => 1。

阅读以下评论后,我修改了我的代码。但是,我仍然不能,我不明白如何获取属性值。

foreach ($xmlArray AS $produkt) {
        foreach ($produkt AS $abc) {
            foreach ($abc AS $singleValue) {

                $data[] = array('net' => (string)$singleValue->price['net']);
            }
        }
    }
    return $data;

输出:Array ( [0] => Array ( [net] => b ) [1] => Array ( [net] => ) [2] => Array ( [net] => ) ) 1

问题是,我不知道有多少次我应该使用foreach,这个param @attributes对我来说很奇怪。谢谢你的帮助。

亲切的问候

2 个答案:

答案 0 :(得分:0)

$data[] = array('net' => $singleValue['net']);

$data[] = array('net' => $singleValue[0]['net']);

尝试将静态索引([0])设为动态

答案 1 :(得分:0)

SimpleXML不生成数组,它会生成一个对象。请查看basic examples in the manual以了解如何使用它。

调试输出中的@attributes只是将子属性与元素分开,实际上并不是如何访问它们。

查看您的调试输出,看起来您真正想要的是这样的:

foreach ( $xml_object->products->product as $product ) {
     $data[] = array('net' => (string)$product->price['net']);
     $data[] = array('net' => (string)$product->srp['net']);
}