0

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
asked Apr 5, 2018 at 16:15
4
  • What is your question exactly? Commented Apr 5, 2018 at 16:20
  • How to format the values in the array properly so i can out to json properly. Commented Apr 5, 2018 at 16:22
  • And what is properly? Commented Apr 5, 2018 at 16:27
  • properly is having the brackets and colons to separate the object and values. Commented Apr 5, 2018 at 16:34

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

i have been trying to achieve: $associative_array = [ 'USD' => 120.00 ]; How can i convert my simple array to the associative array?
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.