2012-03-22 2 views
0

나는 두 개의 XML 파일을 가지고 있습니다. 먼저 첫 번째 XML 파일에서 ID를 가져 와서 두 번째 파일에서 ID와 해당 ID와 관련된 결과를 표시합니다. SQL로이 작업을 수행하려면 다음을 수행하면됩니다.xml 및 php 특정 요소가있는 태그 요소 가져 오기 및 출력

$query = (SELECT * FROM HotelSummary WHERE roomTypeCode = '$id') or die(); 
while($row=mysql_fetch_array($query)){ 
    $name = $row['Name']; 
} 
echo $name; 

어떻게해야합니까? xml 및 php에 있습니까?

+0

웹 페이지 (http://php.net/manual/en/class.domdocument.php)에서 자바 스크립트와 비슷한 방식으로 XML 파일과 상호 작용할 수 있습니다. DOMDocument 객체는 getElementById() 메서드를 지원합니다. – CBusBus

답변

1

SimpleXML을 사용하여 파일의 개체 표현을 만듭니다. 그런 다음 Simple XML 객체의 요소를 반복 할 수 있습니다.

2

DOMDocument documentation을 읽어 보시기 바랍니다. 꽤 무겁지 만 강력합니다. (항상 어떤 일이 일어나는지는 분명하지 않지만, 인터넷은 항상 해결책을 제공합니다.)

첫 번째 문서를 살펴보고 ID를 찾고 XPath를 통해 DOMElement를 찾을 수 있습니다.

1.xml

<?xml version="1.0" encoding="UTF-8"?> 
<articles> 
    <article id="foo_1"> 
     <title>abc</title> 
    </article> 
    <article id="foo_2"> 
     <title>def</title> 
    </article> 
</articles> 

2.xml

<?xml version="1.0" encoding="UTF-8"?> 
<tests> 
    <test id="foo_1" name="top_1"> 

    </test> 
    <test id="foo_2" name="top_2"> 

    </test> 
</tests> 
1

XML 파일의 형식에 따라 :

다음 테스트 파일을 기반으로

<?php 
$dom = new DOMDocument(); 
$dom->load('1.xml'); 

foreach ($dom->getElementsByTagName('article') as $node) { 
    // your conditions to find out the id 
    $id = $node->getAttribute('id'); 
} 


$dom = new DOMDocument(); 
$dom->load('2.xml'); 

$xpath = new DOMXPath($dom); 
$element = $xpath->query("//*[@id='".$id."']")->item(0); 

// would echo "top_2" based on my example files 
echo $element->getAttribute('name'); 

가정 할 경우 :

<xml> 
    <roomTypeCode> 
     <stuff>stuff</stuff> 
     <name>Skunkman</name> 
    </roomTypeCode> 
    <roomTypeCode> 
     <stuff>other stuff</stuff> 
     <name>Someone Else</name> 
    </roomTypeCode> 
</xml> 

그것은이 같은 것이다 : 그것은 일치 할 때,

XML 파일에 연결
$xml = simplexml_load_file('xmlfile.xml'); 
for($i = 0; $i < count($xml->roomTypeCode); $i++) 
{ 
    if($xml->roomTypeCode[$i]->stuff == "stuff") 
    { 
     $name = $xml->roomTypeCode[$i]->name; 
    } 
} 

이, 얼마나 많은 roomTypeCode 항목이 발견은 내 "물건"의 값을 검색하고 제대로, 당신은 그 XML 항목과 관련된 모든 것을 액세스 할 수 있습니다.

관련 문제