dqiz20794 2010-11-22 01:46
浏览 50
已采纳

使用变量访问PHP obj

Updating this question...I'm working on a small CMS. The data is held in XML. I'm trying to access the right image field to update the filename and delete the current image.

Script gets variables based on where it was called from. In this case $page = "homes", $elem = "home" and $field = 0. Below is called on an image upload.

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);
    }
}

This is the structure of the XML file:

<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>

My problem is that $old_img is giving me a "Cannot use string offset as an array" error. If I replace just the $elem and $field variables with values it all works fine.

  • 写回答

2条回答 默认 最新

  • doumei2023 2010-11-22 02:37
    关注

    Alternative code using XPath:

    $load = simplexml_load_file($file);
    $path=$load->xpath('//sections/'.$page.'/'.$elem);
    $path[$field]['img']=$targetFile;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效