Here is my code. I'm trying to scrape a table.
$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);
Here are my results:
[
"USD",
"120.00",
"GBP",
"171.20",
"CAD",
"95.50",
"EUR",
"148.30",
"KYD",
"0.00",
"TTD",
"0.00",
"JPY",
"1.11"
]
Milo
3,4539 gold badges32 silver badges44 bronze badges
-
What is your question exactly?Milo– Milo2018年04月05日 16:20:36 +00:00Commented Apr 5, 2018 at 16:20
-
How to format the values in the array properly so i can out to json properly.Xander– Xander2018年04月05日 16:22:41 +00:00Commented Apr 5, 2018 at 16:22
-
And what is properly?u_mulder– u_mulder2018年04月05日 16:27:54 +00:00Commented Apr 5, 2018 at 16:27
-
properly is having the brackets and colons to separate the object and values.Xander– Xander2018年04月05日 16:34:05 +00:00Commented Apr 5, 2018 at 16:34
1 Answer 1
You're very close.
In order to create JSON from PHP you need an associative array. Right now you have a standard array.
For example:
$associative_array = [
'currency' => 'USD',
'amount' => 120.00
];
OR
$associative_array = [
'USD' => 120.00
];
The exact example for your case:
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);
}
Then you can use json_encode() to encode it to a JSON object:
$json = json_encode($associative_array);
answered Apr 5, 2018 at 16:24
Dylan Pierce
4,6983 gold badges41 silver badges49 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Xander
i have been trying to achieve: $associative_array = [ 'USD' => 120.00 ]; How can i convert my simple array to the associative array?
Dylan Pierce
I just added to my answer, but basically you need to use the
$key part of your foreach loop to build the keys in your associative array.lang-php