2

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.

1
  • 3
    please define "fails". What actually do you get? Commented Nov 22, 2010 at 2:03

2 Answers 2

3

Alternative code using XPath:

$load = simplexml_load_file($file);
$path=$load->xpath('//sections/'.$page.'/'.$elem);
$path[$field]['img']=$targetFile;
Sign up to request clarification or add additional context in comments.

1 Comment

This works great, thanks! I used xpath on another page...still getting used to dealing with xml in php. Much to learn!
3

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. Visually, this is what PHP is looking for:

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

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

2 Comments

For some reason this didn't work. I was originally going down this path.
I must've missed something else then. Meanwhile, XPath is a good alternative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.