2014-06-15 6 views
0

XML 파일에 특정 문자열을 쓰는 데 문제가 있습니다.PHP가 XML 파일에 쓰기

<ePrekrsaji> 
<time> 
<shift hours="48"/> 
</time> 
</ePrekrsaji> 

내가 나던 사용하는 코드가 작동하는 것 :

XML 구조는 이것이다 메시지 catch되지 않은 예외 '예외 : DOMException' '잘못된 문자 : 나는 치명적인 오류가

$my_file = "hours.xml"; 

$hours = 5 

$xml = new DOMDocument(); 
$xml->load($my_file); 
$xml_hours = $xml->createElement($hours); 
$nodes = $xml->getElementsByTagName('shift ') ; 
if ($nodes->length > 0) { 
    $xml->appendChild($xml_hours); 
} 
$xml->save($my_file); 

ERROR 오류 '/var/www/WebDiP/2013_projekti/WebDiP2013_031/skripte/vrijeme.php:17 스택 추적 : # 0 /var/www/WebDiP/2013_projekti/WebDiP2013_031/skripte/vrijeme.php(17) : DOMDocument-> createElement/var/www/WebDiP/2013_projekti/WebDiP2013_031/skrip에 던져진 ('') # 1 {main} te/vrijeme.php on line 17

이 특정 노드에 쓰는 방법은 무엇입니까?

<ePrekrsaji> 
    <time> 
    <shift hours="5"/> 
    </time> 
</ePrekrsaji> 
+0

SimpleXML 클래스를 사용해 보셨습니까? – Cristian

+0

Im XML에별로 좋지 않아서 어떻게 작동하는지 모르겠다. :) – klanc

답변

0

내가 당신에게 SimpleXML 클래스 솔루션을 게시, 그래서 우리는 우리가 속성 shift 요소의 hours을 편집 file_get_contents을 사용하여 파일에서 데이터를 가져 오는, 우리는 file_put_contents와 내용을 저장합니다.

$file = "hours.xml"; 
$xml_data = file_get_contents($file); 
$xml = new SimpleXMLElement($xml_data); 
$xml->time->shift->attributes()->hours = 5; 
file_put_contents($file, $xml->asXML()); 
0

당신은 요소 <5 />, 당신이 올바른 요소 이름의 확신을 만들려고 :

나는 최종 결과가되고 싶어?

나는 당신이 성을 만들고 싶다고 생각합니다. 같은 :

$xml_hours = $xml->createElement('hours', $hours); 
+0

"48"대신 "5"를 쓰도록 기존 구조에 추가하고 싶다. – klanc

0

다음은 수정 된 코드입니다. 첫 번째 shift 요소를 가져 와서 속성을 설정하면됩니다.

$file = "hours.xml"; 
$hours = 6; 

$xml = new DOMDocument(); 
$xml->load($file); 

// get list of all shift elements 
$nodes = $xml->getElementsByTagName('shift'); 
// get first shift element 
$xmlShift = $nodes->item(0); 
// set attribute "hours" 
$xmlShift->setAttribute("hours", $hours); 

$xml->save($file);