php json_decode无法正常工作

时间:2015-08-14 13:43:02

标签: php json

当我使用评论" $ jsonString"解码时字符串它工作得很好。 但是在使用curl后它无法工作,显示Null。

请帮助我。

if (isset($_POST['dkno'])) {
  $dcktNo = $_POST['dkno'];
  $url = 'http://ExampleStatus.php?dkno=' . $dcktNo;
  $myvars = '';

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  $jsonString = curl_exec($ch);
  // $jsonString = '[{"branchname":"BHUBNESHWAR","consignee":"ICICI BANK LTD","currentstatus":"Delivered by : BHUBNESHWAR On - 25/07/2015 01:00","dlyflag":"Y","PODuploaded":"Not Uploaded"}]';

  if ($jsonString != '') {
    $json = str_replace(array('[', ']'), '', $jsonString);
    echo $json;

    $obj = json_decode($json);
        if (is_null($obj)) {
          die("<br/>Invalid JSON, don't need to keep on working on it");
        } else {
          $podStatus = $obj->PODuploaded;
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

在curl之后,我使用以下概念从HTML页面中仅获取JSON数据。

1)fetchData.php

$url = 'http://DocketStatusApp.aspx?dkno=' . $dcktNo;
$myvars = '';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonString = curl_exec($ch);

// now get only value
$dom = new DOMDocument();
$dom->loadHTML($jsonString);
$thediv = $dom->getElementById('Label1');
echo $thediv->textContent;

2)JSONprocess.php

 if (isset($_POST['dkno'])) {
    $dcktNo = $_POST['dkno'];

    ob_start(); // begin collecting output
    include_once 'fetchData.php';
    $result = ob_get_clean(); // Completed collecting output

  // Now it will show & take only JSON Data from Div Tag
  $json = str_replace(array('[', ']'), '', $result);

  $obj = json_decode($json);
  if (is_null($obj)) {
     die("<br/>Invalid JSON, don't need to keep on working on it");
   } else {
    $podStatus = $obj->PODuploaded;
   }
}