2018-06-13 12:17
浏览 62

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

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

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

foreach($dom->getElementsByTagName('p') as $index => $p) {
    $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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongmi5015 2018-06-13 12:57

    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};
    点赞 打赏 评论

相关推荐 更多相似问题