2016-05-02 6 views
0

私は私の 'update_xml.php' ファイルに次のコードを持っている:AJAXとSimpleXMLを

$xml = simplexml_load_file('content.xml'); 
$name = $_POST['name']; 
$xml->home->main->title = $name; 
$output = $xml->asXML(); 
... 

を、私は、このファイルにデータを投稿するAJAXを使用しています:

var name = $(this).val(); 
$.post("update_xml.php", {name: name}, ... 

をすべて、これは正常に動作しますしかし、私はまた、更新される特定のタグを投稿することができる必要があります。例:

var name = $(this).val(); 
$.post("update_xml.php", {name: name, tag: '$xml->home->main->title'}, ... 

$xml = simplexml_load_file('content.xml'); 
$name = $_POST['name']; 
$tag = $_POST['tag']; 
$tag = $name; 

これは明らかに($タグは、現在の文字列である)は動作しません。私はeval()を使用しようとしましたが、これは最善の方法ではありません。何か案は?

答えて

0

XMLドキュメント内のノードをアドレス指定するための言語であるXPathを使用できます。 SimpleXMLはan xpath() methodです。

$.post("update_xml.php", {name: name, path: '/home/main/title}, ... 

そして、あなたはこのようにそれを適用したい::

あなたの例では、XPathはシンプルになり

$xml = simplexml_load_file('content.xml'); 
$xpath_results = $xml->xpath($_POST['path']); 
// $xpath_results is always an array of 0 or more objects 
if (! $xpath_results) ... #HANDLE ERROR 
$tag = $xpath_results[0];