XML

2020-11-20  本文已影响0人  aoshi

XML使用讲解

$doc = new \DOMDocument("1.0","utf8");     //实例化DOMDOCUMENT对象
$doc->formatOutput=true;      //是否格式化输出格式
$rss = $doc->createElement("rss");    //创建节点
$rss->setAttribute('version','2.0');        //添加节点属性
$doc->appendChild($rss);      //将节点加入到父节点
$doc->save($fileName);      //保存到文件
echo $doc->saveXML();       //直接输出到终端

$items=$rss ->getElementsByTagName('item');    //获取某个节点下的子节点
foreach($items as $a){    //遍历节点
            foreach($a->attributes as $name => $value){    //遍历节点属性
                echo $name . '=' . $value;
            }
        }

解析案例

    /**
     * 测试xml
     * */
    public function testXml() {
        $obj = simplexml_load_file('http://mp.youth.cn/xmlDemo/202011200544.xml');
        $obj = $this->objectToArray($obj);
        echo PHP_EOL;
        var_export($obj);
        echo PHP_EOL;
        exit;
    }

    /**
     * 对象转数组
     * */
    function objectToArray($array) {
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = $this->objectToArray($value);
            }
        }
        return $array;
    }

创建案例

/**
     * 生成xml文件
     * */
    public function createXml() {
        $id = I('id','','trim');
        if(!$id) {
            exit('this is over with no id');
        }

        $feedM = FeedModel::gi();
        $articleDetailM = ArticleDetailModel::gi();
        $categoryToChannelM = CategoryToChannelModel::gi();
        $lists = $feedM->where(array('id'=>array('in',$id)))->select();
        if(!$lists) {
            exit('this is over with no data with id');
        }

        $linkBase = 'http://mp.youth.cn';
        $titleBase = '中青号';
        $descriptionBase = '中青号 - 传递社会正能量';

        $doc = new \DOMDocument("1.0","utf8");
        $doc->formatOutput=true;
        $fileName =  'xmlDemo/'. date('Ymdhi') . '.xml';
        $rss = $doc->createElement("rss");    //创建节点 创建RSS版本规范
        $rss->setAttribute('version','2.0');        //添加属性
        $doc->appendChild($rss);        //将节点加入到父节点
        $channel = $doc->createElement("channel");    //创建channel
        $rss->appendChild($channel);
        //标题
        $channelTitle = $doc->createElement("title");
        $titleTextNode = $doc->createTextNode($titleBase);
        $channelTitle->appendChild($titleTextNode);
        $channel->appendChild($channelTitle);
        //链接
        $channelLink = $doc->createElement("link");
        $linkTextNode = $doc->createTextNode($linkBase);
        $channelLink->appendChild($linkTextNode);
        $channel->appendChild($channelLink);
        //简介
        $channelDescription = $doc->createElement("description");
        $descriptionTextNode = $doc->createTextNode($descriptionBase);
        $channelDescription->appendChild($descriptionTextNode);
        $channel->appendChild($channelDescription);

        $fields = array('title','link','category','comments','tags','guid','pubDate','image','description');
//        $fields = array('title','link','category','comments','tags','guid','pubDate','image');
        $imageFields = array('url','title','link');
        foreach($lists as $key => $feedInfo) {
            //item
            $item = $doc->createElement("item");
            $channel->appendChild($item);

            //拼装xml数据体
            $feedInfo['guid'] = hashids_encode($feedInfo['id']);
            $feedInfo['link'] = 'http://mp.youth.cn/article/detail?sign=' . $feedInfo['guid'];
            $feedInfo['category'] = $categoryToChannelM->getNameByTagName($feedInfo['tagname']);
            $feedInfo['comments'] = $feedInfo['abstract'] ? $feedInfo['abstract'] : '';
            $feedInfo['tags'] = $feedInfo['keywords'] ? $feedInfo['keywords'] : '';
            $feedInfo['pubDate'] = date('r',$feedInfo['publish_time']);

            $imageList = json_decode($feedInfo['image_list'],true);
            switch($feedInfo['image_type']) {
                case 1:
                    $imageList = $imageList['one_image'];
                    break;
                case 2:
                    $imageList = $imageList['three_image'];
                    break;
                case 3:
                    $imageList = $imageList['large_image'];
                    break;
            }
            foreach($imageList as $ikey => $imageDetail) {
                $imageList[$key]['title'] = $descriptionBase;
                $imageList[$key]['link'] = $linkBase;
            }
            $imageNum = count($imageList);
            if($imageNum == 2) {
                $imageList = array_shift($imageList);
            } else if($imageNum > 3) {
                $imageList = array_slice($imageList,0,3);
            }
            $feedInfo['image'] = $imageList;
            $feedInfo['description'] = $articleDetailM->getFieldById($feedInfo['id'],'content');

            //组装ITEM
            foreach($fields as $field) {
                switch($field) {
                    case 'image':
                        //组装item下的image
                        foreach($feedInfo[$field] as $imageInfo) {
                            $itemField = $doc->createElement($field);
                            $item->appendChild($itemField);

                            foreach($imageFields as $imageFieldStr) {
                                $imageField = $doc->createElement($imageFieldStr);
                                $fieldTextNode = $doc->createTextNode($imageInfo[$imageFieldStr]);
                                $imageField->appendChild($fieldTextNode);
                                $itemField->appendChild($imageField);
                            }
                        }
                        break;
                    default:
                        $itemField = $doc->createElement($field);
                        $fieldTextNode = $doc->createTextNode($feedInfo[$field]);
                        $itemField->appendChild($fieldTextNode);
                        $item->appendChild($itemField);
                        break;
                }
            }

        }
//        $doc->save($fileName);      //保存到文件
        echo $doc->saveXML();       //直接输出到终端
        echo PHP_EOL . $fileName . PHP_EOL;
        exit('this is over');
    }
上一篇下一篇

猜你喜欢

热点阅读