2012-09-06 5 views
-2

가능한 중복 :
PHP xpath - find element with a value and also get elements before and after element구문 분석 SimpleXML을 자식 값을 기준으로

나는 다음과 같은 XML이 : 위의 예에서

<Table> 
    <ID>100</ID> 
    <Name>Fridge</Name> 
    <Description>A cool refrigerator</Description> 
</Table> 
<Table> 
    <ID>100</ID> 
    <Name>Fridge</Name> 
    <Description>Latest Refrigerator</Description> 
</Table> 
<Table> 
    <ID>200</ID> 
    <Name>Fridge</Name> 
    <Description>Another refrigerator</Description> 
</Table> 

를, 내가 좀하고 싶습니다 ID가 100 인 노드에 대한 이름 W 설명의 하위 값. xml 파일에는 약 1000 개의 테이블 노드가 있습니다.

전체 XML을 구문 분석하고 ID가 100 인 노드에 대해서만 이름 및 설명 값을 얻을 수 있습니까?

$source = 'Tables.xml'; 
$xmlstr = file_get_contents($source); 
$sitemap = new SimpleXMLElement($xmlstr); 

$sitemap = new SimpleXMLElement($source,null,true); 

foreach($sitemap as $url) { 

    if($url->ID == '100') 
    { 
     echo 'Name: '.(string)$url->Name.', Description: '.(string)$url->Description.'<br>'; 
    } 
} 
+1

XPath와 XML에 대한 많은 질문이 있으므로, 질문해야합니다. 무엇을 시도 했습니까? – Gordon

+1

http://codepad.org/EI6JZtau – Gordon

+0

@Gordon 편집 한 질문에서 위의 코드를 시도했습니다. –

답변

2

당신이 그들을 모두 Table 태그와 루프를 얻는 경우는 매우 간단되어야한다 :

지금까지, 나는 다음과 같은 코드, 내가 원하는 것을 줄 수없는 시도

// Assuming you already loaded the XML into the SimpleXML object $xml 
$names_and_descriptions = array(); 
foreach ($xml->Table as $t) { 
    if ($t->ID == 100) { 
    echo $t->Name . " " . $t->Description . "\n"; 
    // Or stick them into an array or whatever... 
    $names_and_descriptions[] = array(
     'name'=>$t->Name, 
     'description'=>$t->Description 
    ); 
    } 
} 
var_dump($names_and_descriptions); 
관련 문제