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 に答える