在我的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})
如何避免错误?
答案 0 :(得分:1)
您只有一个p_0
个对象,并且您正在尝试访问p_1
中不存在的$str
现在,如果您只是想避免错误,那么您可以使用isset()
你可以替换像这样的条件
if(isset($json->{$id})) {
$p->nodeValue = $json->{$id};
}