这是我的代码。我正试图刮一张桌子。
$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"
]
答案 0 :(得分:1)
你非常接近。
要从PHP创建JSON,您需要associative array
。现在你有一个标准阵列。
例如:
$associative_array = [
'currency' => 'USD',
'amount' => 120.00
];
OR
$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);