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"
]
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);
Related
I am not getting any output from the bottom half as I was expecting. I can grab the top table's data, but I am also trying to grab the bottom table data and place encode them into json. The columns I need to grab are
1. Week Date Home Away At Notes
<?php
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML(file_get_contents('https://www.leagueleader.net/sharedreport.php?operatorid=98&code=bc155b01-7492-412d-aa75-3c1e357248f1'));
$doc->strictErrorChecking = false;
$pre = [];
$keys = ['team', 'div', 'team-site-name', 'site-address', 'site-phone'];
$keys2 = ['week', 'date', 'home', 'away', 'at', 'notes'];
foreach ($doc->getElementsByTagName('table') as $k => $table) {
if (strpos($table->getAttribute('class'), 'report') === false) {
continue;
}
foreach ($table->getElementsByTagName('tr') as $i => $tr) {
if ($tr->parentNode->nodeName === 'thead') continue; // skip headers
$row_values = [];
foreach ($tr->childNodes as $td) {
$text = trim($td->nodeValue);
if ($text === '') continue;
$row_values[] = $text;
}
if($k == 1 ){
$row_values = array_combine($keys, $row_values);
}else if($k == 2 ){
unset($row_values[1]);
$row_values = array_combine($keys2, $row_values);
}
$pre[$row_values['name']][] = $row_values;
}
}
$combined = [];
foreach($pre as $week => $row){
$combined[$name] = [
"week"=> $week,
"team"=> $row[0]['team'],
"div"=> $row[0]['div'],
"team-site-name" => $row[0]['team-site-name'],
"site-address" => $row[0]['site-address'],
"site-phone" => $row[0]['site-phone'],
//"week" => $row[1]['week'],
"date" => $row[1]['date'],
"home" => $row[1]['home'],
"away" => $row[1]['away'],
"at" => $row[1]['at'],
"notes" => $row[1]['notes']
];
}
echo '<pre>'.json_encode($combined, JSON_PRETTY_PRINT).'</pre>';
?>
Here is the output
{
"": {
"week": "",
"team": "1",
"div": "A",
"team-site-name": "Team 01Freer Bar",
"site-address": "\u00a07355 Michigan Ave Detroit, MI 48210",
"site-phone": "\u00a03138993699",
"date": null,
"home": null,
"away": null,
"at": null,
"notes": null
}
}
To get the data from the second table with the matches, I've changed the processing to use XPath. This extracts the <tr> tags from the body of the second table with class='report' (using //table[#class='report'][2]/tbody/tr).
So this will return all of the rows in the body of the table. Then extract all of the <td> elements and pick out the details in the row. If there is a week/date present it just overwrites the current data, if there are match details it creates a row on the output...
$xpath = new DOMXPath($doc);
$reportRow = $xpath->query("//table[#class='report'][2]/tbody/tr");
$matches = [];
$week = '';
$date = '';
foreach ($reportRow as $row) {
$cells = $row->getElementsByTagName("td");
// Set week and date if present in the current row
$week = trim($cells[0]->textContent)?:$week;
$date = trim($cells[1]->textContent)?:$date;
// Extract the other details
$teamHome = trim($cells[2]->textContent);
$teamAway = trim($cells[3]->textContent);
$at = trim($cells[4]->textContent);
$notes = trim($cells[5]->textContent);
// If there are some match details, the store them
if ( !empty($teamHome) ) {
$matches[] = ["week" => $week, "date" => $date,
"teamHome" =>$teamHome, "teamAway" =>$teamAway,
"at" => $at, "notes" => $notes
];
}
}
print_r($matches);
This gives...
Array
(
[0] => Array
(
[week] => 1
[date] => 09/10/2019
[teamHome] => Team 01
[teamAway] => BYE
[at] => BYE
[notes] =>
)
I Want to convert this php results in to JSON.
for ($i = 0; $i < (count($getnodays)); $i++)
{
$category = $getctgry[$i];
$Priority = $getpriotity[$i];
$NoOfDays = $getnodays[$i];
$StDate = $date1[$i];
$EdDate = $date2[$i];
}
Results Required to be in :
{
"Category": "Category",
"Priority": "Priority1",
"StDate": "1/1/2016",
"EdDate": "5/1/2018"
},{
"Category": "Category",
"Priority": "Priority1",
"StDate": "1/1/2016",
"EdDate": "5/1/2018"
},{
"Category": "Category",
"Priority": "Priority1",
"StDate": "1/1/2016",
"EdDate": "5/1/2018"
}
In your loop, create a new array occurance each iteration.
Then use json_encode() to turn that array into a valid JSON string.
$json = [];
for ($i = 0; $i < (count($getnodays)); $i++) {
$json[] = ['Category' => $getctgry[$i],
'Priority' => $getpriotity[$i],
'NoOfDays' => $getnodays[$i],
'StDate' => $date1[$i],
'EdDate' => $date2[$i],
];
}
echo json_encode($json);
I have this json source file:
{
"results":
[
{
"movie_title":"A Monster Calls",
"cinema":"downtown"
},
{
"movie_title":"A Monster Calls",
"cinema":"uptown"
},
{
"movie_title":"A Monster Calls",
"cinema":"downtown"
},
{
"movie_title":"A Monster Calls",
"cinema":"downtown"
}
]
}
and I am writing my array like this (simplified for clarity):
$json_data = json_decode($html, true);
for($i = 0; $i < count($json_data['results']); $i++) {
$movieTitle = $json_data['results'][$i]["movie_title"];
$cinema = $json_data['results'][$i]["cinema"];
$moviesList[]= array(
"movieTitle" => $movieTitle,
"cinema" => $cinema
);
}
But what I want to do is output 2 separate arrays. One is all films showing in "downtown" cinema, and the other array all films showing in "uptown". The order in the json file will change, so I have to do it by name.
What's the best way to do this?
$downtownArray = array();
$uptownArray = array();
$json_data = json_decode($html, true);
for($i = 0; $i < count($json_data['results']); $i++) {
$movieTitle = $json_data['results'][$i]["movie_title"];
$cinema = $json_data['results'][$i]["cinema"];
if ($cinema == 'uptown') {
$uptownArray[]= array(
"movieTitle" => $movieTitle,
"cinema" => $cinema
);
} else {
$downtownArray[]= array(
"movieTitle" => $movieTitle,
"cinema" => $cinema
);
}
}
foreach ($json_data['results'] as $result) {
$cinema = $result['cinema'];
$moviesList[$cinema] []= [
"movieTitle" => $result['movie_title'],
// ...
];
}
The code classifies the results by the cinema field and stores them into $moviesList array. So, for example, the uptown results will be stored into $moviesList['uptown'].
You may try something like this
$json_data = json_decode($html, true);
$moviesDwn=array();
$moviesUp=array();
for($i = 0; $i < count($json_data['results']); $i++) {
$movieTitle = $json_data['results'][$i]["movie_title"];
$cinema = $json_data['results'][$i]["cinema"];
if ($json_data['results'][$i]["cinema"]='uptown')
$moviesUp[]= array(
"movieTitle" => $movieTitle,
"cinema" => $cinema
);
else if ($json_data['results'][$i]["cinema"]='updown')
$moviesDwn[]= array(
"movieTitle" => $movieTitle,
"cinema" => $cinema
);
}
First of all please , FIXyou JSON ,as it has some extra comma and then try with below codes
If you want to just separate the two array than use foreach(){};
foreach ($json_data['results'] as $result) {
$DownTown_List[$result['cinema']] []= $result['movie_title'];
}
OR
if you want to do other operation with the Indexes then use for(){};
for($i = 0; $i < count($json_data['results']); $i++) {
if($json_data['results'][$i]["cinema"] === "downtown"){
$DownTown_List["downtown"][] = $json_data['results'][$i]["movie_title"];
}
if($json_data['results'][$i]["cinema"] === "uptown"){
$DownTown_List["uptown"][] = $json_data['results'][$i]["movie_title"];
}
}
echo "<pre>";print_r($DownTown_List);exit;
OUTPUT
Array
(
[downtown] => Array
(
[0] => A Monster Calls
[1] => A Monster Calls
[2] => A Monster Calls
)
[uptown] => Array
(
[0] => A Monster Calls
)
)
I need a proper JSON file with "geo_langitude", "geo_latitude", "adress" & "url" values
I have wp database with post_meta "property" - "geo_langitude" "geo_latitude" & "address" in there.
my file is smth like that
<?php
function return_markers($count) {
$query = new WP_Query('post_type=property&posts_per_page=-1&orderby=menu_order&order=DESC&post_status=publish');
$array = array();
$i = 0;
for ($i = 0; $i< $count; $i++) {
$elem = array(
't' => 'string '.$i,
'x' => get_post_meta($post->ID,'geo_latitude',true),
'y' => get_post_meta($post->ID,'geo_longitude',true),
'z' => $i
);
$array[] = $elem;
}
echo json_encode($elem);
};
return_markers($i);
?>
It's my first time using JSON so I have troubles and I don't know where. =(
with random markers work perfectly:
<?php
function return_markers($count) {
$array = array ();
for ($i = 0; $i< $count; $i++) {
$elem = array(
't' => 'string '.$i,
'x' => 23 + (rand ( 0 , 10000 ) / 10000) * 5,
'y' => 56.2 + (rand ( 0 , 10000 ) / 10000) * 0.8,
'url' => '#map_redirect_'.$i,
'z' => $i
);
$array[] = $elem;
}
echo json_encode($array);
};
return_markers(23);
?>
I want to create an array in a for-loop so i can adjust the size ($i) of the array.
I've tried this:
$array = array();
for($i = 1; $i <= 5; $i++) {
array_push($array,
$i => array(
"id" => "",
"option" => ""
)
);
}
But I get the following error:
Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in ...
I'v also tried to make it a string by doing $i."" on line 4 but that doesn't seem to work either. Does anyone know why?
More idiomatic would be:
$array = array();
for($i = 1; $i <= 5; $i++) {
$array[$i] = array(
"id" => "",
"option" => "") ;
}
However note that this will give you array indexes from 1-5. Arrays are usually indexed from 0:
$array = array();
for($i = 0; $i < 5; $i++) {
$array[$i] = array(
"id" => "",
"option" => "") ;
}
But this can be done without specifying the key:
$array = array();
for($i = 1; $i <= 5; $i++) {
$array[] = array(
"id" => "",
"option" => "") ;
}
try this:
$array = array();
for($i = 1; $i <= 5; $i++) {
$array[$i] = array(
"id" => "",
"option" => ""
);
}
Remove the $i =>
$array = array();
for($i = 1; $i <= 5; $i++) {
array_push($array, array(
"id" => "",
"option" => ""
)
);
}