Example of mutual conversion between xml and json in php

Source: Internet
Author: User
This article mainly introduces php's mutual conversion between xml and json, and analyzes the principles and implementation skills of php's xml-to-json conversion and json-to-xml conversion based on examples, it has some reference value. This document describes how php converts xml to json. We will share this with you for your reference. The details are as follows:

Use php to convert xml and json:

For related functions, see The php Manual.

1. See xml below

 
 
  
   
    
Zhang San
   
   
    
Male
   
   
    
26
   
  
  
   
    
Tank
   
   
    
     
Yes
    No
   
   
    
26
   
  
 

II. Convert xml into json

Use simplexml

Public function xml_to_json ($ source) {if (is_file ($ source) {// judge whether the file is passed or the xml string $ xml_array = simplexml_load_file ($ source );} else {$ xml_array = simplexml_load_string ($ source) ;}$ json = json_encode ($ xml_array); // php5 and later versions. for earlier versions, see JSON. phpreturn $ json ;}

3. convert json to xml

Recursive functions

Public function json_to_xml ($ source, $ charset = 'utf8') {if (empty ($ source) {return false;} // php5, and above. if it is an earlier version, view JSON. php $ array = json_decode ($ source); $ xml = ''; $ xml. = $ this-> change ($ array); return $ xml;} public function change ($ source) {$ string = ""; foreach ($ source as $ k =>$ v) {$ string. = "<". $ k. ">"; // determines whether it is an array, or if (is_array ($ v) | is_object ($ v )) {// is an array or a recursive call to the image $ string. = $ this-> change ($ v);} else {// Get tag data $ string. = $ v;} $ string. = "";} return $ string ;}

The preceding method json_to_xml can support Aaaa , Not supported Aaaaa You can understand the code.


For more articles about examples of php implementation of mutual conversion between xml and json, refer to PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.