0

xml.php

    <?xml version='1.0' encoding='UTF-8'?>
    <product xmlns='http://tempuri.org/xmlrp_feed.xsd'>
    <product_features title = 'Main Features'>
    <feature_item>
    <feature_type><![CDATA[Copier Features]]></feature_type>
    <description><![CDATA[Copier description1]]></description>
    </feature_item>
    <feature_item>
    <feature_type><![CDATA[Copier Features]]></feature_type>
    <description><![CDATA[Copier description2]]></description>
    </feature_item>
    <feature_item>
    <feature_type><![CDATA[Facsimile Features]]></feature_type>
    <description><![CDATA[Facsimile description1]]></description>
    </feature_item>
    <feature_item>
    <feature_type><![CDATA[Facsimile Features]]></feature_type>
    <description><![CDATA[Facsimile description2]]></description>
    </feature_item>
    </product_features>
    </product>

PHP代码

    $xml = simplexml_load_file('xml.php','SimpleXMLElement', LIBXML_NOCDATA); 
    foreach($xml as $rows)
    {    
        foreach($rows as $row){ 
                       echo "<pre>";
                      print_r($row);
                       echo "</pre>";
        }
    }

输出

        SimpleXMLElement Object
    (
        [feature_type] => Copier Features
        [description] => Copier description1
    )

    SimpleXMLElement Object
    (
        [feature_type] => Copier Features
        [description] => Copier description2
    )

    SimpleXMLElement Object
    (
        [feature_type] => Facsimile Features
        [description] => Facsimile description1
    )

    SimpleXMLElement Object
    (
        [feature_type] => Facsimile Features
        [description] => Facsimile description2
    )

需要这样的输出

      SimpleXMLElement Object
    (
        [feature_type] => Copier Features
        [description] => Copier description1
                         Copier description2  
    )
    SimpleXMLElement Object
    (
        [feature_type] => Facsimile Features
        [description] => Facsimile description1
                         Facsimile description2
    )
4

1 回答 1

1

像这样做:

$xml = simplexml_load_string($xmlstr,'SimpleXMLElement', LIBXML_NOCDATA);

$x = count($xml->product_features->feature_item)-1;
$ft = ''; $d = '';

for ($x ; $x >= 0 ; $x--) {

    if ($ft == (string)$xml->product_features->feature_item[$x]->feature_type) {

        $xml->product_features->feature_item[$x]->description = $xml->product_features->feature_item[$x]->description . " $d";

    } else {

        $ft = (string)$xml->product_features->feature_item[$x]->feature_type;
        $d = (string)$xml->product_features->feature_item[$x]->description;
        unset($xml->product_features->feature_item[$x]);
    }   
}

echo "<pre>";
var_dump($xml);
echo "</pre>";

添加说明,中间有空格。
看现场演示:http ://codepad.viper-7.com/qLrlUp

于 2013-03-24T00:33:35.640 回答