2016-06-03 7 views
1

У меня есть массив следующим образом:PHP преобразовать массив в XML

[0] => Array 
     (
      [Project] => Array 
       (
        [ExternalProjectID] => 53 
        [ProjectName] => Doon Creek 
        [Location] => Array 
         (
          [Address] => 123 Fake Street 
          [City] => Toronto 
          [Province] => ON 
          [Latitude] => 43.0000 
          [Longitude] => -80.0000 
         ) 

        [Website] => http://www.website.com/our-communities.php?newcommunity=53 
        [ContactInformation] => Array 
         (
          [ContactPhone] => 555-5555 
          [ContactEmail] => [email protected] 
          [SalesOfficeAddress] => 123 Fake Street 
          [SalesOfficeCity] => Toronto 
          [SalesOfficeProvince] => ON 
         ) 

       ) 

     ) 

Сейчас я пытаюсь тайному это XML точно, как это выглядит в массиве, как проект должен быть узел со всем внутри, Локация также должен быть узлом со всем внутри массива Location внутри этого узла вместе с ContactInformation.

Это то, что у меня есть:

$xml = new SimpleXMLElement(); 

$node = $xml->addChild('Projects'); 

array_to_xml($newArray, $node); 

echo $xml->asXML(); 
die(); 

function array_to_xml($array, &$xml) { 
    foreach($array as $key => $value) { 
     if(is_array($value)) { 
      if(!is_numeric($key)){ 
       $subnode = $xml->addChild("$key"); 
       array_to_xml($value, $xml); 
      } else { 
       array_to_xml($value, $xml); 
      } 
     } else { 
      $xml->addChild("$key","$value"); 
     } 
    } 
} 

но проект, расположение и ContactInformation возвращение, как например, так:

<Projects> 
     <Project /> 
     <ExternalProjectID>53</ExternalProjectID> 
     <ProjectName>Doon Creek</ProjectName> 
     <Location /> 
     <Address>123 Fake St.</Address> 
     <City>Toronto</City> 
     <Province>ON</Province> 
     <Latitude>43.0000</Latitude> 
     <Longitude>-80.000</Longitude> 
     <Website>http://www.website.com/our-communities.php?newcommunity=53</Website> 
     <ContactInformation /> 
     <ContactPhone>555-5555</ContactPhone> 
     <ContactEmail>[email protected]</ContactEmail> 
     <SalesOfficeAddress>123 Fake Street</SalesOfficeAddress> 
     <SalesOfficeCity>Toronto</SalesOfficeCity> 
     <SalesOfficeProvince>ON</SalesOfficeProvince> 
     <Project /> 
</Projects> 

Мой вопрос, как я могу исправить мой XML-выход?

+2

Вы упомянули [это] (http://stackoverflow.com/questions/1397036/how-to-convert-array-to-simplexml)? – Thamilan

+1

Второй ответ сработал для меня. – user979331

ответ

2

Почти у него было это! Вы просто должны были пройти $subnode, не $xml в рекурсивном вызове функции:

// XML BUILD RECURSIVE FUNCTION 
function array_to_xml($array, &$xml) {   
    foreach($array as $key => $value) {    
     if(is_array($value)) {    
      if(!is_numeric($key)){ 
       $subnode = $xml->addChild($key); 
       array_to_xml($value, $subnode); 
      } else { 
       array_to_xml($value, $subnode); 
      } 
     } else { 
      $xml->addChild($key, $value); 
     } 
    }   
} 

// EXAMPLE ARRAY 
$newArray = array(
       "Project" => 
        array("ExternalProjectID" => 53, 
         "ProjectName" => "Doon Creek", 
         "Location" => 
         array ("Address" => "123 Fake Street", 
           "City" => "Toronto", 
           "Province" => "ON", 
           "Latitude" => 43.0000, 
           "Longitude" => -80.0000), 
         "Website" => 
         "http://www.website.com/our-communities.php?newcommunity=53", 
         "ContactInformation" => 
         array("ContactPhone" => "555-5555", 
           "ContactEmail" => "[email protected]", 
           "SalesOfficeAddress" => "123 Fake Street", 
           "SalesOfficeCity" => "Toronto", 
           "SalesOfficeProvince" => "ON") 
         ) 
       ); 

// CREATING XML OBJECT 
$xml = new SimpleXMLElement('<Projects/>'); 
array_to_xml($newArray, $xml); 

// TO PRETTY PRINT OUTPUT 
$domxml = new DOMDocument('1.0'); 
$domxml->preserveWhiteSpace = false; 
$domxml->formatOutput = true; 
$domxml->loadXML($xml->asXML()); 

echo $domxml->saveXML(); 

Выходной

<?xml version="1.0"?> 
<Projects> 
    <Project> 
    <ExternalProjectID>53</ExternalProjectID> 
    <ProjectName>Doon Creek</ProjectName> 
    <Location> 
     <Address>123 Fake Street</Address> 
     <City>Toronto</City> 
     <Province>ON</Province> 
     <Latitude>43</Latitude> 
     <Longitude>-80</Longitude> 
    </Location> 
    <Website>http://www.website.com/our-communities.php?newcommunity=53</Website> 
    <ContactInformation> 
     <ContactPhone>555-5555</ContactPhone> 
     <ContactEmail>[email protected]</ContactEmail> 
     <SalesOfficeAddress>123 Fake Street</SalesOfficeAddress> 
     <SalesOfficeCity>Toronto</SalesOfficeCity> 
     <SalesOfficeProvince>ON</SalesOfficeProvince> 
    </ContactInformation> 
    </Project> 
</Projects> 
0

REFER

<?php 
    // function defination to convert array to xml 
    function array_to_xml($data, &$xml_data) { 
     foreach($data as $key => $value) { 
      if(is_array($value)) { 
       if(is_numeric($key)){ 
        $key = 'item'.$key; //dealing with <0/>..<n/> issues 
       } 
       $subnode = $xml_data->addChild($key); 
       array_to_xml($value, $subnode); 
      } else { 
       $xml_data->addChild("$key",htmlspecialchars("$value")); 
      } 
     } 
    } 

    // initializing or creating array 
    $data = array('total_stud' => 500); 

    // creating object of SimpleXMLElement 
    $xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>'); 

    // function call to convert array to xml 
    array_to_xml($data,$xml_data); 

    //saving generated xml file; 
    $result = $xml_data->asXML('/file/path/name.xml'); 

    ?> 

Documentation on SimpleXMLElement::asXML used in this snippet

Смежные вопросы