2011-04-24 53 views
0

我在'item_detail'(data.html)字段中輸入了15個字符,但是我想在xml文件(item.xml)的'itemdetail'元素中只存儲10個字符我該怎麼做那?在xml文件中存儲html表單值

data.html ----

<form> 
    <p>Id:<input type="text" name= "id" size="10" /> </p> 
    <p>Item Detail:<textarea name="item_detail" rows="3" cols="50" ></textarea></p> 
    <input name="submit" type = "button" onClick = "getData('data.php','info', id.value, ,item_detail.value)" value = "Add Item" /> 

</form>  

<div id="info"> </div> 

data.js -------

var xhr = createRequest(); 
function getData(dataSource, divID, id,itemd) { 
if(xhr) { 
var obj = document.getElementById(divID); 
var requestbody ="idd="+encodeURIComponent(id)+"&itd="+encodeURIComponent(itemd); 
xhr.open("POST", dataSource, true); 
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
xhr.onreadystatechange = function() { 
if (xhr.readyState == 4 && xhr.status == 200) { 
obj.innerHTML = xhr.responseText; 
} // end if 
} // end anonymous call-back function 
xhr.send(requestbody); 
} // end if 
} // end function getData() 

data.php文件-----------

$id= $_POST["idd"]; 
$item_detail= $_POST["itd"]; 


      $xml = new DomDocument(); 
      $xml->load("item.xml"); 
      $xml->formatOutput = true; 
      $items = $xml->firstChild;  
      $item = $xml->createElement('item'); 
      $items->appendChild($item); 
      $id = $xml->createElement('id'); 
      $itemdetail = $xml->createElement('itemdetail'); 
      $item->appendChild($id); 
      $id->nodeValue = $id; 
      $item->appendChild($itemdetail); 
      $ItemDetail->nodeValue = $item_detail; 


      $xml->save("item.xml"); 

      } 
+0

你想存儲*首*十個字符,還是最後*十個?你想要保存比輸入少五個字符嗎?你能提供你想要實現的例子嗎?順便說一句,使用POST請求,你應該在用encodeURIComponent編碼字符串後用''替換'%20'。 – 2011-04-24 12:25:05

回答

1

你可以使用PHP substr

$item_detail= substr($_POST["itd"], 0,10); 

作爲一個附註,你應該考慮清理$ _POST數據。

編輯

我已經整理出來你的變量名,你與XML,其中覆蓋後瓦爾瓦爾

data.php

<?php 
$post_id= $_POST["idd"]; 
$post_item_detail = substr($_POST["itd"], 0,10); 

$xml = new DomDocument(); 
$xml->load("item.xml"); 

$xml->formatOutput = true; 

$items = $xml->documentElement; 
$itemsLength = $items->getElementsByTagName('item'); 
for ($i = 0; $i < $itemsLength->length; $i++) { 
$itm = $items->getElementsByTagName('item')->item($i); 
$oldItem = $items->removeChild($itm); 
} 


$items = $xml->firstChild;  
$item = $xml->createElement('item'); 
$items->appendChild($item); 
$id = $xml->createElement('id'); 
$itemdetail = $xml->createElement('itemdetail'); 
$item->appendChild($id); 
$id->nodeValue = $post_id; 
$item->appendChild($itemdetail); 
$itemdetail->nodeValue = $post_item_detail; 

$xml->save("item.xml"); 

?> 

item.xml

<?xml version="1.0" encoding="UTF-8"?> 
<doc> 

</doc> 
+0

我想將'item_detail'的前10個字符輸入到xml文件的'itemdetail'元素中 – ayman 2011-04-24 12:36:31

+0

@thomas,我嘗試使用ur代碼,但它給出了一個錯誤'parse error:syntax error,unexpected'='in data.php在線2 – ayman 2011-04-24 12:49:43

+0

更新了我的原始答案。這應該可以解決你的問題。 – 2011-04-24 12:56:38