简单的xml不支持循环到foreach

时间:2014-02-16 15:55:45

标签: php for-loop foreach simplexml

我有以下脚本读取XML。但它在for循环后停止。如果我删除循环它运行完美。

我做错了什么或者我能以其他方式实现这个目标吗?

脚本

$xml=simplexml_load_file("test.xml");

foreach($xml->product as $child){
    echo 'Title:'.$child->name.'<br>';//title
    echo 'Price:'.$child->price.'<br>';//title
    echo 'image:'.$child->images->image.'<br>';//image
    echo 'category:'.$child->categories->category.'<br>';//categorie

    foreach( $child->properties->property as $property ){            
        if( $child->properties->property->attributes()->name =='brand'){
            echo $child->properties->property->value.'<br>';
        }
    }
}

XML

<product ID="000000000000052993">
    <name> Title product</name>
    <price currency="EUR">29.99</price>
    <URL>http://www.url.nl</URL>
    <images>
        <image>product/5/2/52993_2.jpg</image>
    </images>
    <description><![CDATA[description.]]>
    </description>
    <categories>
        <category>catt</category>
    </categories>
    <properties>
        <property name="brand">
            <value>PHILIPS</value>
        </property>
        <property name="deliveryTime">
            <value>5</value>
        </property>
        <property name="User1">
        </property>
        <property name="User2">
        </property>
        <property name="shipping_cost">
            <value>0.00</value>
        </property>
        <property name="User3">
        </property>
        <property name="EAN">
            <value>8727900831733</value>
        </property>
    </properties>
    <variations/>
</product>

1 个答案:

答案 0 :(得分:0)

让它成为另一个foreach循环:

foreach( $child->properties as $property ){
    if( $property->attributes()->name == 'brand'){
        echo $property->value;
    }
    if( $property->attributes()->name == 'deliveryTime'){
        echo $property->value;
    }
}