doubeishuai6598 2015-12-05 19:35
浏览 7

解析和XML产品提要

I have an XML product feed that I am parsing with PHP to load products into a database.

I need to get each element into an array of $products = array() such as:

$products[AttributeID] = value

This is what I have so far:

I am using simplexml and I have got most of it:

    $xml = simplexml_load_file($CatalogFileName) or die("can't open file " . $CatalogFileName);

    foreach($xml->children() as $products) { 
        foreach($products->children() as $product) {
            $new_product = array();
            $new_product[sku] = "AS-" . $product->Name;
            foreach($product->Values->Value as $node) { 
                $node_name = preg_replace('/\s+/', '', $node[AttributeID]);
                $new_product[$node_name] = $node[0];  <--THIS IS NOT WORKING: $node[0] returns an array I only want the data in each attribute.
            }
            foreach($product->AssetCrossReference as $node) { 
                $new_product[image] = "http://www.xxxxxxxx.com/images/items/fullsize/" . $node[AssetID] . ".jpg";
            }
            print_r($new_product); 
        }
    }

Here is an image of one product node: XML

Can someone provide me with a little help here? I do a lot of PHP programming but this is the first time I am dealing with XML

  • 写回答

1条回答 默认 最新

  • dsvtnz6350 2015-12-05 19:45
    关注

    You can do it with DOMDocument.loadXML() and DOMDocument.getElementsByTagName():

    $doc = new DOMDocument();
    $doc->loadXML( "<your-xml/>" );
    
    $products = [];
    foreach ( $doc->getElementsByTagName( "Product" ) as $el ) {
        $p = handleProduct( $el );   
        $products[ $p->id ] = $p;
    }
    
    function handleProduct( DOMElement $el ) {
       return (object) [
           "ID" => $el->getAttribute( "ID" ),
           ....
       ];
    }
    
    评论

报告相同问题?