[PHP][Class]利用DOMDocument获取XML内容[已验证][原创]

    技术2022-05-19  28

      目前只完成了一种格式的获取,其他的方法可对Class进行扩展格式如下

           <style>          <styleinfo>               <stylecode>060211101</stylecode>               <stylename>时尚优雅修身休闲便西</stylename>              <styleclass>外套/单西/全部商品</styleclass>             .....            </styleinfo>        </style>

    <?php /** * 获取xml文件内容 * * $xmlFile xml文件地址-可以url也可是本地相对路径 */ class DomXml { //xml对象 private $xmlObj; function __construct($xmlFile){ $this->xmlObj= new DOMDocument(); if (!is_object($this->xmlObj)) die("Create DOMDocument Error!"); $this->load( $xmlFile ); } private function load($xmlFile){ if (!$this->xmlObj->load( $xmlFile )) die("Load Xml Error!!!"); } /** * 获得名为$elementName的节点值的集合 * * @param $elementName 节点名称 * @return array */ public function getElementVal($elementName){ return $this->xmlObj->getElementsByTagName( $elementsName ); } /** * 获得特定格式的xml节点的值 * * <mce:style><!-- <styleinfo> <stylecode>060211101</stylecode> <stylename>时尚优雅修身休闲便西</stylename> <styleclass>外套/单西/全部商品</styleclass> ..... </styleinfo> --></mce:style><style mce_bogus="1"> <styleinfo> <stylecode>060211101</stylecode> <stylename>时尚优雅修身休闲便西</stylename> <styleclass>外套/单西/全部商品</styleclass> ..... </styleinfo> </style> * * @param $elementsName 父节点名称 例:styleinfo * @param $params 参数数组 例:array('name'=>'stylename','code'=>'stylecode') * @return 结果数组 */ public function getVal($elementsName,$params){ $elements = $this->getElementVal( $elementsName ); foreach ($elements as $k=>$element){ foreach ($params as $kk=>$param){ $elementChild = $element->getElementsByTagName($param); $results[$k][$kk] = $elementChild->item(0)->nodeValue; } } return $results; } } ?>


    最新回复(0)