简体   繁体   English

使用变量访问PHP obj

[英]Accessing PHP obj with variables

Updating this question...I'm working on a small CMS. 正在更新此问题...我正在开发小型CMS。 The data is held in XML. 数据以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. 在这种情况下,$ 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);
    }
}

This is the structure of the XML file: 这是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>

My problem is that $old_img is giving me a "Cannot use string offset as an array" error. 我的问题是$ old_img给我一个“不能使用字符串偏移量作为数组”的错误。 If I replace just the $elem and $field variables with values it all works fine. 如果我仅将$ elem和$ field变量替换为值,则一切正常。

PHP is interpreting the [$field] offset as part of the variable $elem and not the entire property $load->sections->$page->$elem , which is probably where your problem lies. PHP将[$field]偏移解释为变量$elem一部分,而不是整个属性$load->sections->$page->$elem ,这可能是您的问题所在。 Visually, this is what PHP is looking for: 从视觉上看,这就是PHP寻找的东西:

// The character at the 0th ($field) position of 'home' ($elem) is 'h'
'h'['img']

Which causes that error you're seeing because string offsets are strings, not arrays. 这会导致您看到该错误,因为字符串偏移量是字符串,而不是数组。

Try this instead. 试试这个吧。 Notice the curly braces around $elem . 注意$elem周围的花括号。

        $old_img = $load->sections->$page->{$elem}[$field]['img'];
        $load->sections->$page->{$elem}[$field]['img'] = $targetFile;

Alternative code using XPath: 使用XPath的替代代码:

$load = simplexml_load_file($file);
$path=$load->xpath('//sections/'.$page.'/'.$elem);
$path[$field]['img']=$targetFile;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM