2014-10-08 1 views
0

이전에 수행 한 simplexml 코드를 업데이트하는 데 도움이 필요합니다. 구문 분석하는 XML 파일은 새로운 방식으로 형식이 지정되었지만 탐색 방법을 알아낼 수는 없습니다. 기존 XML 형식의SimpleXML : 속성이있는 부모와 문제가 발생했습니다.

예 :

<?xml version="1.0" encoding="UTF-8"?> 
<pf version="1.0"> 
<pinfo> 
    <pid><![CDATA[test1 pid]]></pid> 
    <picture><![CDATA[http://test1.image]]></picture> 
</pinfo> 
<pinfo> 
    <pid><![CDATA[test2 pid]]></pid> 
    <picture><![CDATA[http://test2.image]]></picture> 
</pinfo> 
</pf> 

다음 새 XML 형식 ("카테고리 명은"추가주의) :

<?xml version="1.0" encoding="UTF-8"?> 
<pf version="1.2"> 
<category name="Cname1"> 
    <pinfo> 
    <pid><![CDATA[test1 pid]]></pid> 
    <picture><![CDATA[http://test1.image]]></picture> 
    </pinfo> 
</category> 
<category name="Cname2"> 
    <pinfo> 
    <pid><![CDATA[test2 pid]]></pid> 
    <picture><![CDATA[http://test2.image]]></picture> 
    </pinfo> 
</category>  
</pf> 

을하지 않고 구문 분석에 대한 이전 코드 아래에 XML에서 "카테고리 이름"을 추가 한 이후로 작동합니다.

$pinfo = new SimpleXMLElement($_SERVER['DOCUMENT_ROOT'].'/xml/file.xml', null, true); 
foreach($pinfo as $resource) 
{ 
    $Profile_id = $resource->pid; 
    $Image_url = $resource->picture; 

    // and then some echo´ing of the collected data inside the loop 
} 

내가 추가하거나 완전히해야 할 일은 무엇입니까? ferent? xpath, children 및 애트리뷰트별로 분류했지만 행운은 없었습니다. SimpleXML은 항상 내게 수수께끼였습니다.

답변

0

이전에 루트 요소에있는 모든 <pinfo> 요소를 통해 반복했다 :

foreach ($pinfo as $resource) 

지금 모든 <pinfo> 요소는 <category> 요소로 루트 요소에서 이동했다. 이제 먼저 이러한 요소를 조회해야합니다

foreach ($pinfo->xpath('/*/category/pinfo') as $resource) 

는 IT보다 좀 더 변화를 할 수 있도록 지금 잘못 $pinfo이 방법으로 조금 서라는 변수 :

$xml = new SimpleXMLElement($_SERVER['DOCUMENT_ROOT'].'/xml/file.xml', null, true); 
$pinfos = $xml->xpath('/*/category/pinfo'); 

foreach ($pinfos as $pinfo) { 
    $Profile_id = $pinfo->pid; 
    $Image_url = $pinfo->picture; 
    // ... and then some echo´ing of the collected data inside the loop 
} 
+0

이것이 좋은 방법 인 것 같습니다. xpath를 사용하면 모든 것이 아닌 특정 카테고리를 선택할 수 있습니까? – voldsomenterprise

+0

네, 그렇게 할 수 있습니다. [SimpleXML : 특정 속성 값을 갖는 요소 선택하기] (http://stackoverflow.com/q/992450/367456)를 참조하십시오. – hakre

0

XML 파일을로드 할 때 category 요소는 자체 배열로 존재합니다. 파싱에 사용 된 XML은에 포함되어 있습니다. 현재 코드를 다른 코드 foreach으로 감싸기 만하면됩니다. 그 외에는 변할 것이별로 없습니다.

foreach($pinfo as $category) 
{ 
    foreach($category as $resource) 
    { 
     $Profile_id = $resource->pid; 
     $Image_url = $resource->picture; 
     // and then some echo´ing of the collected data inside the loop 
    } 
} 
+0

이 답변 주셔서 감사합니다! 나는 그것이 꽤 간단하다는 것을 알았지 만 각 요소가 배열로 존재한다는 것을 결코 알지 못했습니다. – voldsomenterprise

관련 문제