使用以下代码段,我使用 php 简单的 xml 对象提要从 xml 中检索节点,而不是在给定的父项上检索第一个子元素并将其转换为数组。我的问题:我想获取在洞 XML 对象中具有最多子元素的子元素,并且目标应该转换为数组
/*
* Retrive XML Nodes from Feed
*
*/
public function getXMLNodes() {
$xml = simplexml_load_file($this->config[0]->link);
switch (strtolower($this->config[0]->affiliate)) {
case 'case1':
$nodes = $xml->product[0]; //here stead of first object I should get that one which has most of chlidren
break;
case 'case2':
$nodes = $xml->productItems->productItem[0];
break;
default :
break;
}
$nodes = $this->xml2array($nodes);
return $nodes;
}
/*
* Convert Simple XML Object to array
*
* @xml SimpleXMLObject
*
*/
function xml2array($xml) {
$arr = array();
foreach ($xml as $element) {
$tag = $element->getName();
$e = get_object_vars($element);
if (!empty($e)) {
$arr[$tag] = $element instanceof SimpleXMLElement ? $this->xml2array($element) : $e;
} else {
$arr[$tag] = trim($element);
}
}
return $arr;
}
example XML //在这种情况下,第二个拥有最多的孩子
<?xml version="1.0" encoding="UTF-8"?>
<products>
<product>
<name></name>
<productUrl></productUrl>
<warranty/>
<availability></availability>
<inStock/>
<shippingCost></shippingCost>
<deliveryTime></deliveryTime>
<weight/>
<size/>
<brand/>
<model/>
<ean/>
<upc/>
<isbn/>
<condition></condition>
<mpn/>
<techSpecs/>
<manufacturer></manufacturer>
<programName></programName>
<programLogoPath></programLogoPath>
<programId></programId>
<fields>
<AlsoIncludes></AlsoIncludes>
<Carrier></Carrier>
<modelID></modelID>
<Offertype></Offertype>
<Processor></Processor>
<Service></Service>
<ShippingTax></ShippingTax>
<StandardImage155x155></StandardImage155x155>
<StandardImage200x200></StandardImage200x200>
<Systemtype></Systemtype>
</fields>
</product>
<product>
<name></name>
<productUrl></productUrl>
<imageUrl></imageUrl>
<description></description>
<price></price>
<currency></currency>
<merchantCategoryName></merchantCategoryName>
<sku></sku>
<shortDescription/>
<promoText/>
<previousPrice></previousPrice>
<warranty/>
<availability></availability>
<inStock/>
<shippingCost></shippingCost>
<deliveryTime></deliveryTime>
<weight/>
<size/>
<brand/>
<model/>
<ean/>
<upc/>
<isbn/>
<condition></condition>
<mpn/>
<techSpecs/>
<manufacturer>Dell</manufacturer>
<programName></programName>
<programLogoPath></programLogoPath>
<programId></programId>
<fields>
<AlsoIncludes></AlsoIncludes>
<Carrier></Carrier>
<modelID></modelID>
<Offertype></Offertype>
<Processor></Processor>
<Service></Service>
<ShippingTax></ShippingTax>
<StandardImage155x155></StandardImage155x155>
<StandardImage200x200></StandardImage200x200>
<Systemtype></Systemtype>
</fields>
</product>
</products>