更新这个问题...我正在开发一个小型 CMS。数据以 XML 形式保存。我正在尝试访问正确的图像字段来更新文件名并删除当前图像。
脚本根据调用位置获取变量。在本例中,$page = "homes"、$elem = "home"和 $field = 0。下面在图像上传时调用。
if (!empty($_FILES)) {
$field = $_POST['field'];
$tempFile = $_FILES['upload']['tmp_name'];
$targetFile = "img/sections/".$_POST['page']."/";
$targetFile .= basename($_FILES['upload']['name']);
if (move_uploaded_file($tempFile,$targetFile)) {
$file = "spice.xml";
$load = simplexml_load_file($file);
$old_img = $load->sections->$page->$elem[$field]['img'];
$load->sections->$page->$elem[$field]['img'] = $targetFile;
file_put_contents($file, $xml->saveXML());
unlink($old_img);
}
}
这是 XML 文件的结构:
<spice>
<sections>
<homes>
<home img="img/sections/home/img1.jpg"/>
<home img="img/sections/home/img2.jpg"/>
<home img="img/sections/home/img3.jpg"/>
</homes>
</sections>
</spice>
我的问题是 $old_img 给我一个“不能使用字符串偏移作为数组”错误。如果我仅将 $elem 和 $field 变量替换为值,则一切正常。
最佳答案
使用 XPath 的替代代码:
$load = simplexml_load_file($file);
$path=$load->xpath('//sections/'.$page.'/'.$elem);
$path[$field]['img']=$targetFile;
关于php - 使用变量访问 PHP obj,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4241583/