首页 文章

在PHP中回显特定的JSON节点

提问于
浏览
1

好的,我把RSS写成了JSON文件https://www.dannny0117.com/.well-known/api/news2.php

它起作用,因为它从RSS源返回输出为JSON . 现在,我想用PHP echo 只打印一些元素 .

根据JSON,我需要抓取 channel item titleguid ,因为这些是我要输出的内容 .

我只需要第一个帖子 Headers 和链接,但我的代码不会接受它因为我不完全知道如何访问该东西

这是我正在使用的代码,我认为应该回应但不是

<?php 

$url = "https://www.dannny0117.com/.well-known/api/news2.php";
$content = file_get_contents($url);
$json = json_decode($content, true);

$title = $content['channel']['item'][0]['title'];
$link= $content['channel']['item'][0]['guid'];

echo $title , $link;

?>

更新:这不是编码或unicode字符的问题,主要问题是我的代码CANT从所需的JSON中读取项目 .

2 回答

  • 0

    你可以查看这个链接here,它关于预定义的常量,通常当你处理没有拉丁字母时,你可以有这种混乱 . 尝试使用JSON_UNESCAPED_UNICODE,这将解决您的问题 . 你可以使用这样的东西:

    $json_output = json_decode($content, true, JSON_UNESCAPED_UNICODE);
    

    如你所说它不起作用所以你会尝试添加这个:

    $options = array('http' => array(
             'header' => 'Accept-Charset: UTF-8'
             )
          ); $context = stream_context_create($options);
    
    $url = "https://www.dannny0117.com/.well-known/api/news2.php"; 
    $content= file_get_contents($url, false, $context); 
    $json = json_decode($content, true,JSON_UNESCAPED_UNICODE);
    
  • 0

    你犯了2个错误:

    1)您的json字符串中包含UTF-8字符 .

    2)您在变量 $json 中输出了 json_decode() 字符串,但您使用的是 $content .

    请使用以下代码 .

    $url = "https://www.dannny0117.com/.well-known/api/news2.php";
    $content = file_get_contents($url);
    $enc = mb_detect_encoding($content);
    
    if($enc == 'UTF-8') {
      $content = preg_replace('/[^(\x20-\x7F)]*/','', $content);    
    }    
    
    $json = json_decode($content,true);
    $title = $json['channel']['item'][0]['title'];
    $link  = $json['channel']['item'][0]['guid'];
    echo "<pre>";
    print_r([$title , $link]);
    

相关问题