我在使用函数替换XML文件中的问题和答案元素时遇到了一些问题.我做了很多研究学习php dom,但是我正忙着制作这个功能.问题是当我试图通过属性id获取父元素行时它返回null或当我使用xpath时它返回一个空对象.我得到正确的父元素后,我不知道该函数是否正常工作,但这是我认为的下一步.
我的XML看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<row id="1">
<question>Wat doet de vuilnisman?</question>
<answer>Hij tilt de vuilnisbak in de vuilnisauto.</answer>
</row>
<row id="2">
<question>Wat zegt de tandarts vaak?</question>
<answer>U mag nu spoelen.</answer>
</row>
</root>
Run Code Online (Sandbox Code Playgroud)
和我的PHP功能:
//modifies rows
function modifyRows($file, $rowIds, $rowText) {
$xmlDoc = new DOMDocument();
$xmlDoc->preserveWhiteSpace = false;
$xmlDoc->formatOutput = true;
$xmlDoc->load($file);
foreach($rowIds as $rowId) {
$parent = $xmlDoc->getElementById($rowId);
for($i=0;$i<count($rowText);$i++) {
$newQ = $xmlDoc->createElement('question');
$qText = $xmlDoc->createTextNode($rowText[$i]);
$qText = $newQ->appendChild($qText);
$newA = $xmlDoc->createElement('answer');
$aText = $xmlDoc->createTextNode($rowText[$i++]);
$aText = $newA->appendChild($aText); …Run Code Online (Sandbox Code Playgroud) 我在使用xml时遇到了一些问题.我知道这是一个简单的问题,但我找到的答案并没有解决我的问题.问题是,当我使用php domdocument将é或ä或其他特殊字符添加到我的xml文件时,它将é保存为xE9,将ä保存为xE4.我不知道这是否可以,但是当我想显示输出时,它会在这些地方显示问号.我试了很多.就像删除和添加php domdocument中de xml标头中的编码一样.我也尝试使用file_get_contents并使用php utf-8_decode来获取xml.我尝试使用iso intead,但没有解决我的问题.相反,我有时会得到php xml解析错误.我必须做错事,但是什么?多数民众赞成我的问题以及如何解决这个问题.我的xml文件如下所示:xE9和xE4有黑色背景.
<?xml version="1.0" encoding="UTF-8"?>
<root>
<row id="1">
<question>blah</question>
<answer>blah</answer>
</row>
<row id="2">
<question>xE9</question>
<answer>xE4</answer>
</row>
</root>
Run Code Online (Sandbox Code Playgroud)
和我的php xml类的一部分
function __construct($filePath) {
$this->file = $filePath;
$this->label = array('Vraag', 'Antwoord');
$xmlStr = file_get_contents($filePath);
$xmlStr = utf8_decode($xmlStr);
$this->xmlDoc = new DOMDocument('1.0', 'UTF-8');
$this->xmlDoc->preserveWhiteSpace = false;
$this->xmlDoc->formatOutput = true;
//$this->xmlDoc->load($filePath);
$this->xmlDoc->loadXML($xmlStr);
}
Run Code Online (Sandbox Code Playgroud)
这是添加新行功能
//creates new xml row and saves it in xml file
function addNewRow($question, $answer) {
$nextAttr = $this->getNextRowId();
$parentNode = $this->xmlDoc->documentElement;
$rowNode = $this->xmlDoc->createElement('row');
$rowNode = …Run Code Online (Sandbox Code Playgroud)