Products
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