【问题标题】:PHP Warning: Illegal string offset 'tag'PHP 警告:非法字符串偏移 'tag'
【发布时间】:2016-05-21 15:38:23
【问题描述】:

我正在尝试修复我刚接触的程序中的一些错误:

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

strtoupper($children[$randomc]["tag"]) 我收到错误:

Warning: Illegal string offset 'tag'

为什么会发生这种情况,我该如何纠正?如果需要,我可以添加更多代码。

【问题讨论】:

  • $xmlnode 没有元素“标签”。做var_dump($xmlnode)看看里面有什么
  • $xmlnode 不是数组,而是字符串。您可能想研究使用函数将其拆分为数组。

标签: php string offset


【解决方案1】:

您的$xmlnode['children'] 是一个字符串,而不是一个数组。

它正在寻找类似以下结构的东西:

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

但你实际上是在给它$xmlnode['children'] = "I am a string";

编辑:完整答案:

您首先需要检查$xmlnode['children']数组中的当前项是否为数组,而不是字符串,然后只处理数组的键。

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

【讨论】:

  • 这是 var_dump 的一部分:{ [0]=> string(1) " " [1]=> array(3) { ["tag"]=> string(2) "li " ["attributes"]=> string(0) "" ["value"]=> string(16) "给我讲个故事。" } [2]=> string(1) " " [3]=> array(3) { ["tag"]=> string(2) "li" ["attributes"]=> string(0) "" [ "value"]=> string(19) "哦,你是个诗人。" } [4]=> string(1) " " [5]=> array(3) { ["tag"]=> string(2) "li" ["attributes"]=> string(0) "" [ "value"]=> string(20) "我不明白。" } [6]=> 字符串(1)“”
  • 感谢您的信息,我提供了您的问题的工作示例以及工作解决方案。
  • 谢谢,这解决了错误。希望我不会掩盖一个更大的问题。
猜你喜欢
  • 2019-07-28
  • 2013-04-11
  • 2012-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多