2017-12-13 6 views
0

XML 파일을 반복하고 그 값으로 배열 된 노드를 배열 (key => value)에 저장하려고합니다. 또한 전달 된 노드를 추적하기를 원합니다 (array (users_user_name => "myName", users_user_email => "myEmail") 등).xml 파일을 반복하는 재귀 PHP 함수가 필요합니다.

이 작업을 수행하는 방법을 알고 있지만 문제가 있습니다. 모든 노드에는 자식이있을 수 있으며 해당 자식에는 자식 등이있을 수 있습니다. 그래서 마지막 자식에 도달 할 때까지 반복적으로 자식을 반복하는 재귀 함수가 필요합니다.

지금까지 나는이있어 :

//loads the xml file and creates simpleXML object 
     $xml = simplexml_load_string($content); 

     // for each root value 
     foreach ($xml->children() as $children) { 
      // for each child of the root node 
      $node = $children; 
      while ($children->children()) { 
       foreach ($children as $child) { 

        if($child->children()){ 
         break; 
        } 
        $children = $node->getName(); 
        //Give key a name 
        $keyOfValue = $xml->getName() . "_" . $children . "_" . $child->getName(); 
        // pass value from child to children 
        $children = $child; 

        // no children, fill array: key => value 
        if ($child->children() == false) { 
         $parent[$keyOfValue] = (string)$child; 
        } 
       } 
      } 
      $dataObject[] = $parent; 
     } 

는 "휴식;" "자식"은 마지막 자식이 아니라 객체이기 때문에 잘못된 값을 제공하지 못하게하는 것입니다.

+0

XML 구조를 아는 것이 도움이됩니다. – Dormilich

+0

@ Dormilich 사실 그것은 다른 문제입니다. 구조는 가변적입니다. http://api.parariusoffice.nl/export/208/xpat-rentals.xml을 예로 들었습니다. –

답변

0

재귀를 사용하면 '복잡한'처리를 할 수 있지만 문제는 사용자의 위치를 ​​잃어 버리는 것입니다.

여기서 사용하는 함수는 이름과 현재 출력뿐만 아니라 현재 작업중인 노드를 추적하기 위해 몇 가지로 전달되었습니다. 보시다시피 - 메서드는 자식 노드가 있는지 확인하고 함수를 다시 호출하여 각 노드를 처리합니다. 예를 들어, - 그래서 - 마지막 값을 유지합니다 반복 내용 (복수가 있었다 예를 들어 말할 제한 내용에있다

$content = <<< XML 
<users> 
    <user> 
     <name>myName</name> 
     <email>myEmail</email> 
     <address><line1>address1</line1><line2>address2</line2></address> 
    </user> 
</users> 
XML; 

function processNode ($base, SimpleXMLElement $node, &$output) { 
    $base[] = $node->getName(); 
    $nodeName = implode("_", $base); 
    $childNodes = $node->children(); 
    if (count($childNodes) == 0) { 
     $output[ $nodeName ] = (string)$node; 
    } 
    else { 
     foreach ($childNodes as $newNode) { 
      processNode($base, $newNode, $output); 
     } 
    } 
} 

$xml = simplexml_load_string($content); 
$output = []; 
processNode([], $xml, $output); 
print_r($output); 

이 출력합니다 ...이 구현

Array 
(
    [users_user_name] => myName 
    [users_user_email] => myEmail 
    [users_user_address_line1] => address1 
    [users_user_address_line2] => address2 
) 

, 사용자).

0

재귀를 사용하고 싶습니다!

여기에 재귀의 간단한 예입니다 :

function doThing($param) { 
    // Do what you need to do 
    $param = alterParam($param); 
    // If there's more to do, do it again 
    if ($param != $condition) { 
     $param = doThing($param); 
    } 
    // Otherwise, we are ready to return the result 
    else { 
     return $param; 
    } 
} 

당신은 당신의 특정 사용 케이스에이 생각을 적용 할 수 있습니다.

관련 문제