2017-02-07 4 views
1

나는 여러 외부 소스로부터 경제적 및 사회적 통계를 제공하고 데이터베이스 (데이터 분석을 위해)에서 이들을 수집하는 프로그램을 작성 중이다. 데이터의 일부는 XML 형식으로 제공되며 XML 파일의 요소/태그와 속성을 식별하는 데 필요합니다. 특성을 확인하기 위해 getAttribute를 사용하여 시도했다.DOM 객체의 getAttribute가 속성을 반환하지 않는다

문제점 : getElementsByTagName은 작동하지만 getAttribute는 작동하지 않습니다. 셀 요소에서 'Index'특성 값을 검색하려고하면 "Index"특성이 여러 셀 요소에 있어도 ""를 반환합니다. 오류가없고 값이 반환되지 않습니다.

PHP 매뉴얼을 읽고 인터넷을 조사하여 해결책을 찾으려고 노력했지만 성공하지 못했습니다. getAttribute의 반환 값을 반향 또는 var_dump하면 항상 ""이 반환됩니다. 전체 소스 코드를 넣는 대신 XML 파일을 읽는 간단한 버전을 재 작성했습니다.이 버전에서는 특성 (이 경우 'Index'특성)을 반환 할 수없는 동일한 문제가 발생합니다. 어떤 도움이 크게 감사합니다

<Row> 
    <Cell><Data ss:Type="String">AAA</Data></Cell> 
    <Cell ss:Index="3"><Data ss:Type="String">Board of Governors of the Federal Reserve System (US)</Data></Cell> 
    <Cell><Data ss:Type="String">H.15 Selected Interest Rates</Data></Cell> 
    <Cell><Data ss:Type="String">Percent</Data></Cell> 
    <Cell><Data ss:Type="String">Not Seasonally Adjusted</Data></Cell> 
    <Cell><Data ss:Type="String">The Federal Reserve Board has discontinued this series as of October 11, 2016. More information, including possible alternative series, can be found at http://www.federalreserve.gov/feeds/h15.html. </Data></Cell> 
</Row> 

: 여기

<?php 

// Creates new DOMDocument 
$dom = new DOMDocument(); 
// Loads XML file into DOMDocument 
$dom->load('FRED_formatted_list.xml'); 

// Stores all the instances of the Row tag into $rows 
$rows = $dom->getElementsByTagName('Row'); 

// Iterates through all the instances of the Row tag 
foreach($rows as $row) { 

// Stores all the instances of the Cell tag into $cells 
$cells = $row->getElementsByTagName('Cell'); 

// Iterates through all the instances of the Cell tag 
foreach($cells as $cell) { 

    // Checks if the Index attribute exists in the cell tag 
    if($cell->hasAttribute('Index')) { 
     // Stores the value of any instances of the Index attribute 
     $attr = $cell->getAttribute('Index'); 
     // Prints the value of any instances of the Index attribute to screen 
     echo "Value of index attribute: " . $attr . "<br>"; 

    } 
    // Check that the cell tags have been properly identified in the DOM Object 
    echo $cell->nodeValue . "<br>"; 
    // Double checks whether any index values are even found and stored in $attr 
    var_dump($attr) . "<br>"; 
} 
} 
?> 

은 속성 '인덱스'하지 getAttributes에 의해 반환되지에도 존재 함을 보여줍니다 XML 파일의 샘플입니다. 나는 해결책을 요약하고 다른 사람들을 돕기 위해 다시 게시 할 것이다.

+0

당신은'DOMXpath :: evaluate()'도 살펴볼 것을 제안합니다. Xpath를 사용하면 DOM 문서에서 데이터를 훨씬 쉽게 읽을 수 있습니다. – ThW

답변

0

은 XML의 네임 스페이스를 정의

<Row xmlns:ss="something"> 
    <Cell><Data ss:Type="String">AAA</Data></Cell> 
    <Cell ss:Index="3"><Data ss:Type="String">Board of Governors of the Federal Reserve System (US)</Data></Cell> 
    <Cell><Data ss:Type="String">H.15 Selected Interest Rates</Data></Cell> 
    <Cell><Data ss:Type="String">Percent</Data></Cell> 
    <Cell><Data ss:Type="String">Not Seasonally Adjusted</Data></Cell> 
    <Cell><Data ss:Type="String">The Federal Reserve Board has discontinued this series as of October 11, 2016. More information, including possible alternative series, can be found at http://www.federalreserve.gov/feeds/h15.html. </Data></Cell> 
</Row> 

네임 스페이스와 속성의 값을 얻기 위해 다음 코드를보십시오 :

<?php 

    // Creates new DOMDocument 
    $dom = new DOMDocument(); 
    // Loads XML file into DOMDocument 
    $dom->load('FRED_formatted_list.xml'); 

    // Stores all the instances of the Row tag into $rows 
    $rows = $dom->getElementsByTagName('Row'); 
    $attr =''; 
    // Iterates through all the instances of the Row tag 
    foreach($rows as $row) { 

    // Stores all the instances of the Cell tag into $cells 
    $cells = $row->getElementsByTagName('Cell'); 

    // Iterates through all the instances of the Cell tag 
    foreach($cells as $cell) { 
     // Checks if the Index attribute exists in the cell tag 
     if($cell->attributes->getNamedItem('Index')) { 
      // Stores the value of any instances of the Index attribute 
      $attr = $cell->attributes->getNamedItem('Index')->nodeValue; 
      // Prints the value of any instances of the Index attribute to screen 
      echo "Value of index attribute: " . $attr . "<br>"; 

     } 
    // Check that the cell tags have been properly identified in the DOM Object 
    echo $cell->nodeValue . "<br>"; 
    // Double checks whether any index values are even found and stored in $attr 
    var_dump($attr) . "<br>"; 


    } 

} 
+0

실수를 지적 해 주셔서 감사합니다. 이 단순화 된 예제를 소스 코드 ($ 셀이 올바르게 표시되어 있음)에서 다시 작성할 때 나는 약간 엉터리 였음에 틀림 없다. 문제는 수정 후에도 지속됩니다. getAttribute를 사용할 때 여전히 수익이 없습니다. –

+0

향후 리뷰에서주의 분산을 피하기 위해 위의 코드를 편집했습니다 –

+0

업데이트로 각 $ 셀에 var_dump를 시도했으며 XML을로드 할 때 속성이 생략되었다고합니다 DOM 객체에 저장합니다. public 'attributes'=> 문자열 '(객체 값 생략)'(길이 = 22) 그렇다면 XML 파일을 DOM에로드 할 때 속성이 제거 된 이유는 무엇입니까? 목적? –

0

내가 찾은 추가 조사 후이 문제가 발생하여 해결하기 위해 관리되는 다른 사람 그것. XML 셀 태그/요소의 'Index'속성은 'ss :'로 미리 고정되어 있습니다 (XML 파일 추출 방법 <Cell ss:Index="3"><Data ss:Type="String"> 이상). getAttribute가 작동하려면 'ss :'가 포함되어야합니다. 올바른 코드는 내가 완전히 getAttribute가 속성을 식별하는 방법을 이해하지 않습니다 getAttribute('ss:Index') 대신 getAttribute('Index')
것하지만 그이 전에 공간 때문에와 연속 된 문자의 문자열을 검색하다 할 수있다 'SS'할 필요가 포함.