dongnan1899 2015-06-18 01:25
浏览 28
已采纳

json格式与json_encode()

I have been working with json_encode() in PHP and the output is:

{"Inventors:":"Wilson; Nestor Antonio Lagos (Santiago, CL)"}
{"Applicant: ":"Nestor Antonio Lagos  Santiago  N\/A  CL"}
{"Name":"Type"}

And I want the json format like as:

json = {
"Inventors:":"Wilson; Nestor Antonio Lagos (Santiago, CL)",
"Applicant: ":"Nestor Antonio Lagos  Santiago  N\/A  CL",
"Name":"Type"
};

I've tried but always the convertion of my array is the same.

$contents = "<table><tr><td>Row 1 Column 1</td><td>Row 1 Column 2</td></tr><tr><td>Row 2 Column 1</td><td>Row 2 Column 2</td></tr></table>";

$DOM = new DOMDocument;
$DOM->loadHTML($contents);

$items = $DOM->getElementsByTagName('tr');

function tdrows($elements)
{
    $str = "";
    $i = 0;
    foreach ($elements as $element)
    {   
        if($i == 0) {
            $itm = $element->nodeValue;
            $i++;
        } else {
            if(strlen($element->nodeValue) > 1 )
            $array = array($itm => trim($element->nodeValue));
        }
        //$str .= $element->nodeValue . ", ";
    }
    echo json_encode($array);
}
  • 写回答

1条回答 默认 最新

  • 普通网友 2015-06-18 01:33
    关注

    You can create required json output using following snippet:

    <?php
    $people = array();
    $people['Inventors']='Wilson; Nestor Antonio Lagos (Santiago, CL)';
    $people['Applicant']='Nestor Antonio Lagos  Santiago  N\/A  CL';
    $people['Name']='Nestor Antonio Lagos  Santiago  N\/A  CL';
    
    echo json_encode($people);
    ?>
    

    You are receiving output like that because you are creating a new array and inserting into $array. Use following code

    $array[$itm] = trim($element->nodeValue); 
    

    and it will work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题