PHP 구문 분석 xml 형식 데이터 도구 클래스 예제 설명

jacklove
풀어 주다: 2023-04-02 10:00:02
원래의
1739명이 탐색했습니다.

이 문서에서는 주로 PHP 구문 분석 xml 형식 데이터 도구 클래스를 소개하며, xml 형식 데이터 노드를 추가, 획득 및 구문 분석하는 PHP 관련 작업 기술이 필요하면 참조할 수 있습니다.

이 문서의 예에서는 PHP 구문 분석 xml에 대해 설명합니다. 형식 데이터 도구 종류. 참조용으로 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다.

class ome_xml {
  /**
  * xml资源
  *
  * @var    resource
  * @see    xml_parser_create()
  */
  public $parser;
  /**
  * 资源编码
  *
  * @var    string
  */
  public $srcenc;
  /**
  * target encoding
  *
  * @var    string
  */
  public $dstenc;
  /**
  * the original struct
  *
  * @access  private
  * @var    array
  */
  public $_struct = array();
  /**
  * Constructor
  *
  * @access    public
  * @param    mixed    [$srcenc] source encoding
  * @param    mixed    [$dstenc] target encoding
  * @return    void
  * @since
  */
  function SofeeXmlParser($srcenc = null, $dstenc = null) {
    $this->srcenc = $srcenc;
    $this->dstenc = $dstenc;
    // initialize the variable.
    $this->parser = null;
    $this->_struct = array();
  }
  /**
  * Parses the XML file
  *
  * @access    public
  * @param    string    [$file] the XML file name
  * @return    void
  * @since
  */
  function xml2array($file) {
    //$this->SofeeXmlParser('utf-8');
  $data = file_get_contents($file);
    $this->parseString($data);
    return $this->getTree();
  }
  function xml3array($file){
  $data = file_get_contents($file);
  $this->parseString($data);
  return $this->_struct;
  }
  /**
  * Parses a string.
  *
  * @access    public
  * @param    string    data XML data
  * @return    void
  */
  function parseString($data) {
    if ($this->srcenc === null) {
      $this->parser = xml_parser_create();
    } else {
      if($this->parser = xml_parser_create($this->srcenc)) {
        return 'Unable to create XML parser resource with '. $this->srcenc .' encoding.';
      }
    }
    if ($this->dstenc !== null) {
      @xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->dstenc) or die('Invalid target encoding');
    }
    xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);  // lowercase tags
    xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);    // skip empty tags
    if (!xml_parse_into_struct($this->parser, $data, $this->_struct)) {
      /*printf("XML error: %s at line %d",
          xml_error_string(xml_get_error_code($this->parser)),
          xml_get_current_line_number($this->parser)
      );*/
      $this->free();
      return false;
    }
    $this->_count = count($this->_struct);
    $this->free();
  }
  /**
  * return the data struction
  *
  * @access    public
  * @return    array
  */
  function getTree() {
    $i = 0;
    $tree = array();
    $tree = $this->addNode(
      $tree,
      $this->_struct[$i]['tag'],
      (isset($this->_struct[$i]['value'])) ? $this->_struct[$i]['value'] : '',
      (isset($this->_struct[$i]['attributes'])) ? $this->_struct[$i]['attributes'] : '',
      $this->getChild($i)
    );
    unset($this->_struct);
    return $tree;
  }
  /**
  * recursion the children node data
  *
  * @access    public
  * @param    integer    [$i] the last struct index
  * @return    array
  */
  function getChild(&$i) {
    // contain node data
    $children = array();
    // loop
    while (++$i < $this->_count) {
      // node tag name
      $tagname = $this->_struct[$i][&#39;tag&#39;];
      $value = isset($this->_struct[$i][&#39;value&#39;]) ? $this->_struct[$i][&#39;value&#39;] : &#39;&#39;;
      $attributes = isset($this->_struct[$i][&#39;attributes&#39;]) ? $this->_struct[$i][&#39;attributes&#39;] : &#39;&#39;;
      switch ($this->_struct[$i][&#39;type&#39;]) {
        case &#39;open&#39;:
          // node has more children
          $child = $this->getChild($i);
          // append the children data to the current node
          $children = $this->addNode($children, $tagname, $value, $attributes, $child);
          break;
        case &#39;complete&#39;:
          // at end of current branch
          $children = $this->addNode($children, $tagname, $value, $attributes);
          break;
        case &#39;cdata&#39;:
          // node has CDATA after one of it&#39;s children
          $children[&#39;value&#39;] .= $value;
          break;
        case &#39;close&#39;:
          // end of node, return collected data
          return $children;
          break;
      }
    }
    //return $children;
  }
  /**
  * Appends some values to an array
  *
  * @access    public
  * @param    array    [$target]
  * @param    string    [$key]
  * @param    string    [$value]
  * @param    array    [$attributes]
  * @param    array    [$inner] the children
  * @return    void
  * @since
  */
  function addNode($target, $key, $value = &#39;&#39;, $attributes = &#39;&#39;, $child = &#39;&#39;) {
    if (!isset($target[$key][&#39;value&#39;]) && !isset($target[$key][0])) {
      if ($child != &#39;&#39;) {
        $target[$key] = $child;
      }
      if ($attributes != &#39;&#39;) {
        foreach ($attributes as $k => $v) {
          $target[$key][$k] = $v;
        }
      }
      $target[$key][&#39;value&#39;] = $value;
    } else {
      if (!isset($target[$key][0])) {
        // is string or other
        $oldvalue = $target[$key];
        $target[$key] = array();
        $target[$key][0] = $oldvalue;
        $index = 1;
      } else {
        // is array
        $index = count($target[$key]);
      }
      if ($child != &#39;&#39;) {
        $target[$key][$index] = $child;
      }
      if ($attributes != &#39;&#39;) {
        foreach ($attributes as $k => $v) {
          $target[$key][$index][$k] = $v;
        }
      }
      $target[$key][$index][&#39;value&#39;] = $value;
    }
    return $target;
  }
  /**
  * Free the resources
  *
  * @access    public
  * @return    void
  **/
  function free() {
    if (isset($this->parser) && is_resource($this->parser)) {
      xml_parser_free($this->parser);
      unset($this->parser);
    }
  }
}
로그인 후 복사

PS: 참조용으로 XML 작업을 위한 여러 온라인 도구가 있습니다.

OnlineXML/ JSON 상호 변환 도구:
http://tools.jb51.net/code/xmljson

온라인 서식XML/온라인 압축XML:
http://tools.jb51.net /code/ xmlformat

XML온라인 압축/형식 지정 도구:
http://tools.jb51.net/code/xml_format_compress

XML코드 온라인 형식 지정 및 미화 도구:
http://tools.jb51.net/code/xmlcodeformat

관심을 가질 수 있는 기사:

PHP에서 클래스 정적 호출과 범위 확인 연산자의 차이점

스택 예제에 대한 자세한 설명 그리고 배열을 기반으로 PHP에서 구현한 큐 함수

PHP7을 기반으로 한 오류 처리 및 예외 처리 방법에 대한 자세한 설명

위 내용은 PHP 구문 분석 xml 형식 데이터 도구 클래스 예제 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!