Search code examples
phpstringoffset

PHP Warning: Illegal string offset 'tag'


I'm trying to fix some bugs in a program that I'm new to:

if  (strtoupper($xmlnode["tag"])=="RANDOM"){

    $liarray=array();

    $children = $xmlnode["children"];

    for ($randomc=0;$randomc<sizeof($children);$randomc++){
        if (strtoupper($children[$randomc]["tag"]) == "LI"){
            $liarray[]=$randomc;
        }
    }

On the strtoupper($children[$randomc]["tag"]) I get the error:

Warning: Illegal string offset 'tag'

Why this is happening and how might I correct it? I can add more code if needed.


Solution

  • Your $xmlnode['children'] is a string, not an array.

    It's looking for something structured like:

    $xmlnode['children'] = [
                                ['tag' => 'LI'],
                                ['tag' => 'LU'],
                                ['tag' => 'LA'],
                                ['tag' => 'LO'],
                                ['tag' => 'LE'],
                                ['tag' => 'LR'],
                            ];
    

    But you are actually giving it something like $xmlnode['children'] = "I am a string";

    EDIT: Complete answer:

    You first need to check if the current item in the $xmlnode['children'] array is an array, and not a string, then process only the keys that are an array.

    $xmlnode['tag'] = 'RANDOM';
    $xmlnode['children'] = array(
        " ",
        array(
            'tag' => 'li',
            'attributes' => "",
            'value' => "Tell me a story."
        ),
        " ",
        array(
            'tag' => 'li',
            'attributes' => "",
            'value' => "Oh, you are a poet."
        ),
        " ",
        array(
            'tag' => 'li',
            'attributes' => "",
            'value' => "I do not understand."
        ),  
        " "
    );
    
    $liarray = array();
    if  (strtoupper($xmlnode["tag"]) == "RANDOM") {
    
        $children = $xmlnode["children"];
    
        for ($randomc=0; $randomc < sizeof($children); $randomc++) {
            if (is_array($children[$randomc])) {
                if (strtoupper($children[$randomc]["tag"]) == "LI") {
                    $liarray[] = $randomc;
                }
            }
        }
        print_r($liarray);  
    }