且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

XML 复杂解析

更新时间:2023-09-14 11:21:04

你可以试试

$list = groupBy($xml, "WebCategory");
foreach ( $list['Mobiles'] as $product ) {
    printf('<li>%s %s</li>', $product->Code, $product->Name);
}

输出

  • 10000 HTC Wildfire S-A510E
  • 10001 HTC Wildfire
  • 10002 三星 Galaxy S3
  • 10003 三星 Galaxy S2
  • 10004 三星 Galaxy S1
  • 10007 Apple Iphone 4S
  • 10008 Apple Iphone 3G
  • 10012 Sony Erricsson Satio
  • 使用的函数

    function groupBy($xml, $categoryName) {
        $xml = new \SimpleXMLElement($xml);
        $category = array();
        foreach ( $xml as $row ) {
            $attr = $row->attributes();
    
            if (! isset($attr->$categoryName)) {
                trigger_error("$categoryName does not exist in XML");
                break;
            }
    
            $category[(string) $attr->$categoryName][] = $attr;
        }
        return $category;
    }
    

    观看现场演示