繁体   English   中英

如何将php数组正确格式化为json?

[英]How can i properly format php array to json?

这是我的代码。 我想刮一张桌子。

$page = file_get_contents('https://www.jncb.com/Support/Help-Resources/Foreign-Exchange-Services');

$dom = new DOMDocument();
$html = $page;
$data = array();
$fx = array();
$cnt = 0;

libxml_use_internal_errors(true);
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$my_xpath_query = "//table//tbody[contains(@class, 'FxRContainer')]//td";
$result_rows = $xpath->query($my_xpath_query);


foreach ($result_rows as $key=>$result_object) {  
    $data[] = $result_object->nodeValue;
} 

for ($i=0; $i < 28; ++$i) { 
    if( $i % 2 == 0 ) {
        $fx[] = $data[$i];
    }
}

for ($i=0; $i < 14; ++$i) { 
    if ( $i % 2 == 0 ) {
        $fx[$i] = substr($fx[$i], 6);
    }
}

print_r($fx);
echo json_encode($fx, JSON_PRETTY_PRINT); 

这是我的结果:

[
   "USD",
   "120.00",
   "GBP",
   "171.20",
   "CAD",
   "95.50",
   "EUR",
   "148.30",
   "KYD",
   "0.00",
   "TTD",
   "0.00",
   "JPY",
   "1.11"
]

你很亲密

为了从PHP创建JSON,您需要一个associative array 现在,您有了一个标准数组。

例如:

$associative_array = [
    'currency' => 'USD',
    'amount' => 120.00
];

要么

$associative_array = [
   'USD' => 120.00
];

您的情况的确切示例:

foreach($result_rows as $key => $result_object) {
    // took a guess here
    // not entirely sure if you want the $key or the $result_object->nodeValue to be substr'd
    $data[$key] = substr($result_object->nodeValue, 6);
} 

然后,您可以使用json_encode()将其编码为JSON对象:

$json = json_encode($associative_array);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM