Putting arrays in a table using PHP - php

I'm a beginner in PHP and working on an API project which has to get results from a server I connected via API.
I am getting the results, but I would like to have them well arranged in a simple table.
This is what I am getting:
I used the following code:
$api = new SplynxAPI($api_url, $key, $secret);
$locationsApiUrl = "admin/administration/locations";
echo "<pre>";
echo "List locations\n";
$result = $api->api_call_get($locationsApiUrl);
echo "Result: ";
if ($result) {
echo "Ok!\n";
print_r($api->response);
} else {
echo "Fail! Error code: $api->response_code\n";
print_r($api->response);
}
echo "\n-------------------------------------------------\n";
Kindly assist me on this one.

The following code will render your response in a HTML <table>.
$api = new SplynxAPI($api_url, $key, $secret);
$locationsApiUrl = "admin/administration/locations";
$result = $api->api_call_get($locationsApiUrl);
if ($result) {
echo "<table>";
foreach($api->response as $row){
echo sprintf('<tr><td>%s</td><td>%s</td></tr>', $row['id'], $row['name']);
}
echo '</table>';
} else {
echo "Fail! Error code: $api->response_code\n";
print_r($api->response);
}
echo "\n-------------------------------------------------\n";

You are directly getting the response "$api->response" as an array. So simply use a loop and populate it in table as you like.
Ex:
foreach($api->response as $apiData) {
// Your code
}

Related

A way Limit data based upon unique ID

I have a xml file with a listing of trains and each train make up is tied to a specific trainID. I wrote a php script to compile this data into a user readable format but can't figure out a way to set it up to read and report only the data that is associated with the trainID. Im looking to link to the train report page with a url using the train ID. I tried making a function but I don't think that is what i need, as it was not working. Below is a portion of my XML file and list generator.
<ScnLoader xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<trainList>
<TrainLoader>
<trainID>99991</trainID>
<TrainWasAI>false</TrainWasAI>
<DispatchTrainDirection>0</DispatchTrainDirection>
<ManuallyAppliedSpeedLimitMPH>2147483647</ManuallyAppliedSpeedLimitMPH>
<PreviousSignalInstruction>Clear</PreviousSignalInstruction>
<unitLoaderList>
<RailVehicleStateClass>
<rvXMLfilename>R8_CoveredHopper_PS4750_DGHX01.xml</rvXMLfilename>
<unitType>US_Freightcar</unitType>
<currentRoutePrefix>
<int>320</int>
<int>320</int>
</currentRoutePrefix>
<currentTrackSectionIndex>
<int>1365</int>
<int>1365</int>
</currentTrackSectionIndex>
<startNodeIndex>
<int>0</int>
<int>0</int>
</startNodeIndex>
<distanceTravelledInMeters>
<float>76.0736</float>
<float>90.00746</float>
</distanceTravelledInMeters>
<reverseDirection>
<boolean>true</boolean>
<boolean>true</boolean>
</reverseDirection>
<loadWeightUSTons>111.1</loadWeightUSTons>
<destinationTag>BAR HOU</destinationTag>
<unitNumber>571555</unitNumber>
</RailVehicleStateClass>
</unitLoaderList>
</TrainLoader>
</trainList>
</ScnLoader>
php
<?php
$railunit = simplexml_load_file('railUnitList.xml'); //database of railunits
$orders = simplexml_load_file('testdata.xml'); //Where the data comes from to form the list
?><pre><?php print_r($orders); ?></pre><?php
foreach ($orders->TrainLoader->trainID as $trainID){
$trainid = "99991";
}
foreach ($orders->xpath("RailVehicleStateClass") as $traininfo) {
$rvXMLfilename=(string)$traininfo->rvXMLfilename;
$unitType=(string)$traininfo->unitType;
$unitNumber=(int)$traininfo->unitNumber;
$destinationTag=(string)$traininfo->destinationTag;
$loadWeightUSTons=(int)$traininfo->loadWeightUSTons;
$totalUnitCount = $totalUnitCount + 1;
echo "<tr>";
echo "<td align='center'>";
echo $totalUnitCount;
echo "</td>";
echo "<td>";
foreach ($railunit->railUnit as $ru) {
if((string)$ru->rvXMLfilename == $rvXMLfilename){
$message = (string)$ru->reportingMark;
}
}
echo $message;
echo "</td>";
echo "<td>";
echo $unitNumber;
echo "</td>";
echo "<td>";
$message = "Not Found!";
foreach ($railunit->railUnit as $ru) {
if((string)$ru->rvXMLfilename == $rvXMLfilename){
$message = (string)$ru->unitType;
}
}
}
?>
You can add a condition in your XPath expression to retrieve only the node you want :
$railunit = $railunit->xpath("//TrainLoader[trainID = $trainid]")[0]; // retrieve all TrainLoader node that has a child 'trainID' with value '$trainid', then keep only the first one
// whole node
echo $railunit->asXML() ;
// access specific information
echo (string) $railunit->xpath('./ManuallyAppliedSpeedLimitMPH')[0]; // 2147483647

PHP file_get_html on Pinterest - Some seriously weird behaviour

Trying to scrape a bit of basic account info from Pinterest pages (no I'm not scraping pins before I get accused of using this maliciously, it's simply a competitor research tool).
Some accounts work fine with file_get_html, others return completely blank objects and I can't figure out why. I've built the below test code with completely random pages of different sizes to try and do some testing... still no further forward.
It uses Simple HTML DOM and here is my test code trying to figure out why some aren't working.
$pinterestUrl1 = "https://uk.pinterest.com/sfashionality/";
$pinterestUrl2 = "https://uk.pinterest.com/serenebathrooms/";
$pinterestUrl3 = "https://uk.pinterest.com/jenstanbrook/";
$pinterestUrl4 = "https://uk.pinterest.com/homebaseuk/";
$pinterestUrl5 = "https://uk.pinterest.com/thedoifter/";
$pinterestUrl6 = "https://uk.pinterest.com/coolshitibuy/";
$html1 = file_get_html($pinterestUrl1);
$html2 = file_get_html($pinterestUrl2);
$html3 = file_get_html($pinterestUrl3);
$html4 = file_get_html($pinterestUrl4);
$html5 = file_get_html($pinterestUrl5);
$html6 = file_get_html($pinterestUrl6);
echo $pinterestUrl1 . " - "; if (is_object($html1)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl2 . " - "; if (is_object($html2)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl3 . " - "; if (is_object($html3)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl4 . " - "; if (is_object($html4)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl5 . " - "; if (is_object($html5)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl6 . " - "; if (is_object($html6)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
Result:
https://uk.pinterest.com/sfashionality/ - Returns object okay
https://uk.pinterest.com/serenebathrooms/ - Returns object okay
https://uk.pinterest.com/jenstanbrook - Failed
https://uk.pinterest.com/homebaseuk/ - Failed
https://uk.pinterest.com/thedoifter/ - Returns object okay
https://uk.pinterest.com/coolshitibuy/ - Returns object okay
I can't see any reasons why some of these return objects and others don't... and because it's blank I don't even know where to start debugging this kind of thing.
Any ideas at all on this one? Thanks
Simple HTML DOM parser has constant MAX_FILE_SIZE with value 600000 and URLs that you are requesting have slightly more HTML.
You can define MAX_FILE_SIZE with some larger value before including lib, this will produce a PHP notice but HTML will be processed. Code I have tested this with:
<?php
define('MAX_FILE_SIZE', 6000000); //Will produce notice, but we need to define it
include_once './simplehtmldom_1_5/simple_html_dom.php';
$urls = array(
'https://uk.pinterest.com/sfashionality/',
'https://uk.pinterest.com/serenebathrooms/',
'https://uk.pinterest.com/jenstanbrook/',
'https://uk.pinterest.com/homebaseuk/',
'https://uk.pinterest.com/thedoifter/',
'https://uk.pinterest.com/coolshitibuy/',
);
foreach ($urls as $url) {
$content = file_get_contents($url);
$html = str_get_html($content);
echo $url . ' - ';
if (is_object($html)) {
echo 'Returns object okay<br/>';
} else {
echo 'Failed<br/>';
};
}

How to call a Php Function from html

I am using a PHP scraper by using simple PHP DOM library. I wrote a function which scrapes data that I need. How can I call that function from html page? I need to show that data in my html page. I am using AngularJS framework and I am working with views.
Here is my code.
function Islamabad_data(){
// Array Declaration
var isb_hi_temp = new Array();
$fhtml1 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278');
$fhtml1 = str_get_html($fhtml1);
$day6 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278?day=6');
$day6 = str_get_html($day6);
echo "Islamabad Data<br>";
echo" <br>High temperature <br>";
foreach($fhtml1->find('#feed-tabs .temp') as $element){
echo $element->plaintext;
?>
isb_hi_temp.push('<?php echo $element; ?>');
<?php
}
$i=0;
foreach($day6->find('#feed-tabs .temp')as $element)
{
if($i<2)
{
echo $element->plaintext;
?>
isb_hi_temp.push('<?php echo $element; ?>');
<?php
$i++;
}
}
echo isb_data;
}
I know this is not an answer but I've simplified your code. It looks like you want to generate a JavaScript array that can be fetched by Angular. Step 1 one is to properly generate the JSON you need. There were a lot of mistakes in your code -- you cannot intermix JavaScript and PHP in the way that you were doing. Usually in PHP we'll generate an array object using PHP then call json_encode to create the JSON object that will be accessed by the client (in this case, you are using Angular as your client).
function Islamabad_data(){
$fhtml1 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278');
$fhtml1 = str_get_html($fhtml1);
$day6 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278?day=6');
$day6 = str_get_html($day6);
//echo "Islamabad Data<br>";
//echo" <br>High temperature <br>";
$hiTemp = array();
foreach($fhtml1->find('#feed-tabs .temp') as $element){
$hiTemp[] = $element;
}
$i=0;
foreach($day6->find('#feed-tabs .temp')as $element) {
if ($i<2) {
$hiTemp[] = $element;
}
$i++;
}
echo json_encode( $hiTemp );
}
Step 2. Use Angular to call your PHP service. Here is an oversimplified example to help you:
function Hello($scope, $http) {
$http.get('/some/where/somefile.php').
success(function(data) {
$scope.islamabadData = data;
});
}
Also you should really be using Accuweather's API instead of doing data scraping.
http://apidev.accuweather.com/developers/
It might help you:
function loadCitiesData($scope, $http) {
$http.get('/some/where/somefile.php?Islamabad=1').
success(function(data) {
$scope.islamabadData = data;
});
$http.get('/some/where/somefile.php?Lahore=1').
success(function(data) {
$scope.LahoreData = data;
});
}
And your somefile.php file:
<?php
if( !empty($_GET['Islamabad']) ){
$fhtml1 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278');
$fhtml1 = str_get_html($fhtml1);
$day6 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278?day=6');
$day6 = str_get_html($day6);
//echo "Islamabad Data<br>";
//echo" <br>High temperature <br>";
$hiTemp = array();
foreach($fhtml1->find('#feed-tabs .temp') as $element){
$hiTemp[] = $element;
}
$i=0;
foreach($day6->find('#feed-tabs .temp')as $element) {
if ($i<2) {
$hiTemp[] = $element;
}
$i++;
}
echo json_encode( $hiTemp );
}elseif( !empty($_GET['Lahore']) ){
// your code, $yourArray = array('something');
// echo json_encode( $yourArray );
}elseif( !empty($_GET['Multan']) ){
// your code, $yourArray = array('something');
// echo json_encode( $yourArray );
}
?>

GET request variable error in PHP

I have a simple PHP code, as below.
When I try the URL localhost/df.php?result1=bharat, I get the result Bharat, exactly as I want it. But when I try the URL localhost/df.php?result2=bharat, I get an error, meaning my result2 variable was not read like my result1 variable did.
Could you please correct my code so that it works?
<?php
if(isset($_GET['Result1']))
{
$file = $_GET['Result1'];
}
else
{
echo "Error"; exit;
}
echo "$result1";
?>
elseif(isset($_GET['Result2']))
{
$file = $_GET['Result2'];
}
else
{
echo "Error"; exit;
}
echo "$result2";
?>
You have way too many errors in your code. The following is the solution to your problem:
<?php
if(isset($_GET['result1']))
{
$result1 = $_GET['result1'];
echo $result1;
}
elseif(isset($_GET['result2']))
{
$result2 = $_GET['result2'];
echo $result2;
}
else
{
echo "Error";
exit();
}
?>
For the future, I would recommend you to learn PHP and be familiar with the basic syntax, at least, before posting questions about it here.

Getting multiple values out of a database using html/php multiple selector

I am trying to extract multiple values from a row in a table in a mysql database. I want the selector to show the description only, and after the form is submitted, I want to be able to access additional information from that row. I am able to get all of the item_types out into an array, but I am not sure how to add the item_id. I don't want item_id to show up in the html selector.
I tried a few things like array_push. The only way I can think of getting this done is by making one big string in "value" and extracting the parts after the form is submitted.
Here is the function so far:
function createDropdown() {
echo '<select multiple name="items[]">';
try {
$items = mysql_query("SELECT item_id,item_type FROM items");
while ($row = mysql_fetch_assoc($items)) {
echo '<option value="'.$row['item_type'].'"';
echo '>'. $row['item_type'] . '</option>'."\n";
}
}
catch(PDOException $e) {
echo 'No results';
}
echo '</select>';
}
Hmm you can try to generate a lookup table whenever you create a drop-down list:
function createDropdown(&$ddlLookup) {
echo '<select multiple name="items[]">';
try {
$items = mysql_query("SELECT item_id,item_type FROM items");
while ($row = mysql_fetch_assoc($items)) {
echo '<option value="'.$row['item_type'].'"';
echo '>'. $row['item_type'] . '</option>'."\n";
$ddlLookup[$item_type] = $item_id;
}
}
catch(PDOException $e) {
echo 'No results';
}
echo '</select>';
}
Then whenever you need the id for a given description you use that table(array) to get it:
$mainDropdownLUT = array();
createDropdown($mainDropdownLUT);
var_dump($mainDropdownLUT['testCow']);
-> 734
Also, if you need to pass it to another page it can be serialized and added to a hidden field.
$mainDropdownLUT = serialize($mainDropdownLUT);
"<input type="hidden" value =\"$mainDropdownLUT\">"
-------------------------**OTHER PAGE **--------------
$mainDropdownLUT = unserialize($mainDropdownLUT);

Categories