获取Undefined属性:在WordPress插件中的DOM内部使用JSON时出现stdClass :: $ key错误

时间:2018-06-13 12:17:39

标签: php json wordpress domdocument

在我的WordPress插件的主functions.php文件中,我使用以下代码

<?php
$str = '{"p_0":"New first content"}';
$json = json_decode($str);

$html = '<p>First</p><p>Second</p>';
$dom = new DOMDocument;
$html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_use_internal_errors(false);

foreach($dom->getElementsByTagName('p') as $index => $p) {
    $p->setAttribute('id','p_'.$index);
    $id = $p->getAttribute('id');
    if($json->{$id}) {
        $p->nodeValue = $json->{$id};
    }
}

echo $dom->saveXML($dom);
?>

第一段被覆盖但是我得到了错误

Undefined property: stdClass::$p_0 in ... // the line where if($json->{$id})

如何避免错误?

1 个答案:

答案 0 :(得分:1)

您只有一个p_0个对象,并且您正在尝试访问p_1中不存在的$str

现在,如果您只是想避免错误,那么您可以使用isset()

你可以替换像这样的条件

if(isset($json->{$id})) {
    $p->nodeValue = $json->{$id};
}