php multidimensional array to string or table - php

how can I output this array into html table?
for each row I would like to output it like this, within the foreach;
echo "<td>".$lat."</td><td>".$long."</td>";
as per example on https://developer.here.com/documentation/routing-waypoints/topics/quick-start-simple-car.html
I have tried the code
$api_url = "https://wse.api.here.com/2/findsequence.json?start=Berlin-Main-Station;52.52282,13.37011&destination1=East-Side-Gallery;52.50341,13.44429&destination2=Olympiastadion;52.51293,13.24021&end=HERE-Berlin-Campus;52.53066,13.38511&mode=fastest;car&app_id=ID&app_code=CODE";
$api_response = file_get_contents($api_url);
$api_response_decoded = json_decode($api_response, true);
foreach($api_response_decoded as $api_response_decoded_row){
print_r($api_response_decoded_row[0][waypoints]);
}
and also tried
print_r($api_response_decoded_row[0][waypoints][id]);
and also tried
echo($api_response_decoded_row[0][waypoints][id]);
and also tried
implode($api_response_decoded_row[0][waypoints][id]);

Here's one way you could do it if the comments didn't already help you enough.
foreach($api_response_decoded as $api_response_decoded_rows){
foreach ($api_response_decoded_rows[0]['waypoints'] as $waypoint) {
$html = '
<td>'.$waypoint['lat'].'</td>
<td>'.$waypoint['lng'].'</td>
';
echo $html;
}
}

Thanks to commenters and answerers. In case it helps someone else, full working code is therefore;
$api_url = "https://wse.api.here.com/2/findsequence.json?start=Berlin-Main-Station;52.52282,13.37011&destination1=East-Side-Gallery;52.50341,13.44429&destination2=Olympiastadion;52.51293,13.24021&end=HERE-Berlin-Campus;52.53066,13.38511&mode=fastest;car&app_id=ID&app_code=CODE";
$api_response = file_get_contents($api_url);
$api_response_decoded = json_decode($api_response, true);
echo "<table>";
foreach($api_response_decoded as $api_response_decoded_rows){
foreach ($api_response_decoded_rows[0]['waypoints'] as $waypoint) {
$html = '<tr><td>'.$waypoint['sequence'].'</td><td>'.$waypoint['id'].'</td><td>'.$waypoint['lat'].'</td><td>'.$waypoint['lng'].'</td></tr>';
echo $html;
}
}
echo "</table>";

Related

PHP Wont print from external API

I use to go to school for only a short time in programming. A while ago and I'm rusty. I've been trying to re-learn everything by myself and something is bothering me. I'm trying to print out a specific object from an external API but nothing I try seems to work out. I don't really know what to google to get the right answer I am looking for. Anyway here's my code.
<?php
$url = 'http://apis.is/flight?language=en&type=departures';
$json = file_get_contents($url);
$results = json_decode($json, TRUE);
for ($x = 0; $x < count($results); $x++) {
echo $results[$x]['results']['flightNumber']."<br/>";
}
?>
If you do a debug (by the way, learn what is it), you will see, that your $results has one key: result, over which you can iterate with a simple foreach:
foreach ($results['result'] as $item) {
echo $item['flightNumber'];
}
You are trying to access the data returned from the API in the wrong order, do this instead:
<?php
$url = 'http://apis.is/flight?language=en&type=departures';
$json = file_get_contents($url);
$results = json_decode($json, TRUE);
// To loop through an array, use foreach instead of for
// It is easier to use
foreach($results['results'] as $result){
echo $result['flightNumber'].'<br />';
}
?>
<?php
$url = 'http://apis.is/flight?language=en&type=departures';
$json = file_get_contents($url);
$results = json_decode($json, TRUE);
foreach ($results['results'] as $res) {
echo $res['flightNumber']."<br/>";
}
?>

Return html table in php function

I'm new to PHP and I come from Objective-C. I need to create a plugin for WP that returns an HTML table where each row is populated by data from JSON. In essence, as an example, I need to replace echo with return:
$jsonurl = "http://xxxx/club/api/xxxx/category/";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
//print_r ($json_output);
echo "<table>";
foreach ( $json_output->result as $result )
{
echo "<tr><td>".$result->id."</td><td>".$result->categoryKind."</td><td>".$result->ranking."</td>";
}
echo "</table>" ;
That works! I can see output as expected. But for showing table in WP through Shortcode, I need return and no echo. So how can I replace the echo with return?
I tried:
function foobar_func(){
$html= "<table>";
foreach ( $json_output->result as $result )
{
$html. = "<tr><td>".$result->id."</td><td>".$result->categoryKind."</td><td>".$result->ranking."</td>";
}
$html. = "</table>" ;
return $html;
}
add_shortcode( 'foobar', 'foobar_func' );
without success. Any help is welcome.
UPDATE: Same result (no work). I will exit crazy.
function foobar_func($json_output){
$html= "<table>";
foreach ( $json_output->result as $result )
{
$html. = "<tr><td>".$result->id."</td><td>".$result->categoryKond."</td> <td>".$result->ranking."</td>";
}
$html. = "</table>" ;
return $html;
}
add_shortcode( 'foobar', 'foobar_func' );
please try ob_start() method i think it useful to you.
http://php.net/manual/en/function.ob-start.php
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>
Variable scope is your problem here. $json_output isn't accessible within the function.
Change to the following:
function foobar_func(){
global $json_output;
$html= "<table>";
Alternatively to calling it as a global variable, you can pass it within the function call.
function foobar_func($json_output){
And then when you call the function, use foobar_func($json_output)
After investigating I found the way out. But honestly I can't understand why this code works. Thank you all for putting me on the right path.
Code:
function foobar_func($json_output){
$jsonurl = "http://xxxx/club/api/xxx/category/";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
echo "<table>";
foreach ( $json_output->result as $result )
{
echo "<tr><td>".$result->id."</td><td>".$result->categoryKind."</td><td>".$result->ranking."</td>";
}
echo "</table>" ;
return $html;
}
add_shortcode( 'foobar', 'foobar_func' );

How to parse json in php from url

Im new to json, so i gotta ask you a maybe really simple questions.
I've tried searching around but have not found anything I can get to work.
I have called an API and received the data in json.
And now comes my problem parsing it through my php, it "will not find anything."
My code looks like this:
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept: application/vnd.travify.v1+json\r\n"
)
);
$context = stream_context_create($opts);
$url = 'http://oda.ft.dk/api/Sag?$select=titel,Sagskategori/kategori&$expand=Sagskategori';
$output = file_get_contents($url, false, $context);
$string = file_get_contents($url, false, $context);
$result = json_decode($string, true);
$i = -1;
foreach ($result as $data) {
$i++;
echo "#";
echo $i;
echo "<br>";
echo "<b>Test 1:</b>";
echo "<br>";
if(!empty($result[$i]['value']['Sagskategori']['kategori'])){
echo $result[$i]['value']['Sagskategori']['kategori'];
}else{
echo "Intet fundet.";
}
echo "<hr>";
}
The json code can be find here: http://oda.ft.dk/api/Sag?$select=titel,Sagskategori/kategori&$expand=Sagskategori
Can anyone of you see my fail in the code, and get me on the right way :-) ?
Please replace
foreach ($result as $data) {
by
foreach ($result["value"] as $data) {
And now you can iterate to your value array and get all informations from $data
You don't need use $i, $data contains correct $result[$i] value
foreach ($result["value"] as $data) {
echo "#";
echo "<br>";
echo "<b>Test 1:</b>";
echo "<br>";
if(!empty($data['Sagskategori']['kategori'])){
echo $data['Sagskategori']['kategori'];
}else{
echo "Intet fundet.";
}
echo "<hr>";
}
The JSON starts like this:
{
"odata.metadata":"...snip...","value":[
{
So the array is inside the value object.
The correct code should be:
foreach ($result['value'] as $data) {
// snip
if(!empty($result['value'][$i]['Sagskategori']['kategori'])){
echo $result['value'][$i]['Sagskategori']['kategori'];
}
Also, inside the loop, $result['value'][$i]['Sagskategori']['kategori']; is strictly the same as using $data['Sagskategori']['kategori'];.

What makes this jsessionid shows up on this PHP-code result?

I want to do parsing on this site: CiteSeerx Result.
I tried this:
<?php
include('simple_html_dom.php');
$url = 'http://citeseerx.ist.psu.edu/search?q=mean&t=doc&sort=rlv&start=0';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
$html = new simple_html_dom();
$html->load($curl_scraped_page);
foreach ($html->find('div.result h3') as $title) {
echo $title->plaintext . '<br/>';
}
echo '---<br>';
foreach ($html->find('div.result h3 a') as $link) {
echo '\'http://citeseeerx.ist.psu.edu' . $link->href . '<br>';
}
echo '---<br>';
foreach ($html->find('div.pubinfo') as $info){
echo $info->innertext. '<br>';
}
echo '---<br>';
foreach ($html->find('div.snippet') as $snippet){
echo $snippet->innertext. '<br>';
}
?>
It works and gives me what I want, it's just that, this jsessionid=... shows up on every single line of the $link results.
What do I do to make it disappear? I googled for addressing this problem, but all I find is the way to solve it with Java, not PHP.
Thanks.
<a class="remove doc_details" href="/viewdoc/summary;jsessionid=103B4C6E9ADA3C8B17DD64BD57238F9D?doi=10.1.1.160.3832">
because the href in the tag includes the jsession id part :)

php simple html dom parser doesn't return anything

Why won't my script return the div with the id of "pp-featured"?
<?php
# create and load the HTML
include('lib/simple_html_dom.php');
$html = new simple_html_dom();
$html->load("http://maps.google.com/maps/place?cid=6703996311168776503&q=hills+garage&hl=en&view=feature&mcsrc=google_reviews&num=20&start=0&ved=0CFUQtQU&sa=X&ei=sCq_Tr3mJZToygTOmuCGCg");
$ret = $html->find('div[id=pp-featured]');
# output it!
echo $ret->save();
?>
this gets me on my way. Thanks for your help.
<?php
include_once 'lib/simple_html_dom.php';
$url = "http://maps.google.com/maps/place?cid=6703996311168776503&q=hills+garage&hl=en&view=feature&mcsrc=google_reviews&num=20&start=0&ved=0CFUQtQU&sa=X&ei=sCq_Tr3mJZToygTOmuCGCg";
$html = file_get_html($url);
$ret = $html->find('div[id=pp-reviews]');
foreach($ret as $story)
echo $story;
?>
The library always returns an array because it may be possible that more than one item matches the selector.
If you expect only one you should check to ensure the page your analyzing is behaving as expected.
Suggested solution:
<?php
include_once 'lib/simple_html_dom.php';
$url = "http://maps.google.com/maps/place?cid=6703996311168776503&q=hills+garage&hl=en&view=feature&mcsrc=google_reviews&num=20&start=0&ved=0CFUQtQU&sa=X&ei=sCq_Tr3mJZToygTOmuCGCg";
$html = file_get_html($url);
$ret = $html->find('div[id=pp-reviews]');
if(count($ret)==1){
echo $ret[0]->save();
}
else{
echo "Something went wrong";
}

Categories