2

我有一个 xml 文件,我想创建一个表单/表格来使用 PHP 添加、编辑和删除记录。

有什么方法可以创建一个显示所有结果的表,并允许我编辑或删除表示 XML 文件中完整记录的表的特定行?

我希望能够仅使用我的网络浏览器添加/编辑/删除标签,而无需编辑 pc 上的 xml 文件并上传到 FTP ..

我需要用 PHP、javascript 或任何其他方式完成此操作。

请不要给我 simpleXML 的链接,因为我试过这个,但我没有让它工作:(

如果有人可以帮助我,将不胜感激!谢谢!

我的 xml 文件 (scores.xml) 看起来像这样:

<Games>
<Game>
<Header> </Header>
<Row>B</Row>
<Date>07.10.2011 01:05</Date>
<Time>Finished</Time>
<HomeTeam>Team1</HomeTeam>
<Score>1 - 3</Score>
<AwayTeam>Team2</AwayTeam>
<InfoID>info2</InfoID>
<InfoData> </InfoData>
<Other> </Other>
</Game>
</Games>
4

2 回答 2

2

这是一个在没有 SimpleXML 的情况下在 php 中使用 XML 的非常简单的示例,但是 SimpleXML 会容易得多:

<?php
//Load the scores XML file
$scores = new DOMDocument();
$scores -> load('scores.xml');

//Get the <Games> tag
$games = $scores -> getElementsByTagName('Games');

//Create the new <Game> tag (Could probably be done better by first placing everything in an array or something)
$newGame = $scores -> createElement("Game");
$newGame -> appendChild($scores -> createElement("Time", "Finished"));
$newGame -> appendChild($scores -> createElement("Score", "2 - 5"));
$newGame -> appendChild($scores -> createElement("Row", "B"));

//Add the new <Game> tag under the <Games> tag
$games -> item(0) -> appendChild($newGame);

//Save again
$scores -> save('scores.xml');
?>
于 2012-05-17T16:43:21.237 回答
1

您可能没有正确使用 SimpleXML 库。如果您要尝试将内容添加到 Game->Other(当前为空),请以这个简单的示例为例

$xml = <<<XML
<Games>
<Game>
<Header> </Header>
<Row>B</Row>
<Date>07.10.2011 01:05</Date>
<Time>Finished</Time>
<HomeTeam>Team1</HomeTeam>
<Score>1 - 3</Score>
<AwayTeam>Team2</AwayTeam>
<InfoID>info2</InfoID>
<InfoData> </InfoData>
<Other> </Other>
</Game>
</Games>
XML;

// first convert the existing XML into a SimpleXML Object
$xmlObj = new SimpleXMLElement($xml);
echo "<pre>".print_r($xmlObj, true)."</pre>";

// update Other
$xmlObj->Game->Other = "lolz";
echo "<pre>".print_r($xmlObj, true)."</pre>";

// return as XML
$xml = $xmlObj->asXML();
echo "<pre>$xml</pre>\n";

$xml 中的内容现在是完全最新的 XML。现在,如果您有多个游戏,则需要通过执行以下操作遍历 Game 节点:

foreach($xmlObj->Game as $game) $game->Other = "Lolz";

这将使用文本 Lolz 更新每个游戏的 Other 标签。显然这不是很有用,但您会确保通过分配某种标识符或执行一些逻辑来仅更新您想要的节点。无论如何,对于您的基本示例,这应该可以工作,并且应该是解决问题的开始。祝你好运 :)

于 2012-05-17T16:19:10.703 回答