解析和XML产品提要

时间:2015-12-05 19:35:24

标签: php xml xml-parsing

我有一个XML产品Feed,我正在使用PHP进行解析,以将产品加载到database.

我需要将每个元素放入$products = array()的数组中,例如:

$products[AttributeID] = value

这是我到目前为止所做的:

我使用的是simplexml,我已经掌握了大部分内容:

    $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); 
        }
    }

以下是一个产品节点的图片:XML

有人可以在这里给我一些帮助吗?我做了很多PHP编程,但这是我第一次处理XML

1 个答案:

答案 0 :(得分:0)

您可以使用DOMDocument.loadXML()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" ),
       ....
   ];
}