网站优化

网站优化

Products

当前位置:首页 > 网站优化 >

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

GG网络技术分享 2025-03-18 16:12 3


问题描述:

In the main functions.php file of my WordPress plugin I use the following code

<?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);

?>

The first paragraph is overriden but at that I get the error

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

How can I avoid the error?

网友观点:

You have only one p_0 object and you are trying to access p_1 which does not exist in your $str

Now if you just want to avoid error then you can use isset()

you can replace if condition like this

if(isset($json->{$id})) {

$p->nodeValue = $json->{$id};

}

标签:

提交需求或反馈

Demand feedback