Parsing part of a json object with multi levels using PHP - php

If you open the URL, you'll see that it's a very long string of sub objects. I want to extract the values for the 70 position. So far I've been able to extract the first tree without a problem ... But if you go deeper then I don’t get any feedback at all. Please check the code below and tell me, what am I doing wrong?
$url= "https://bwt.cbp.gov/api/waittimes";
$port = file_get_contents($url); // put the contents of the file into a variable
$data = json_decode($port); // decode the JSON feed
echo $data[69]->port_name.'<br>';
echo $data[69]->port_status.'<br>';
echo $data[69]->passenger_vehicle_lanes->maximum_lanes.'<br>';
echo $data[69]->passenger_vehicle_lanes->standard_lanes->lanes_open.'<br>';

The following is working for me:
$url= "https://bwt.cbp.gov/api/waittimes";
$port = file_get_contents($url); // put the contents of the file into a variable
$data = json_decode($port, true); // decode the JSON feed
echo "There are ".count($data)."Ports".PHP_EOL;
$found=false;
foreach ($data as $key => $value) {
//EDIT AFTER COMMENT**
if($value['port_number']==250401){
echo $value['port_name'].' '.$value['crossing_name'].PHP_EOL;
$found=true;
break;
}
}
if(!$found) echo "couldn't find port #";

can you try to change json_decode($port, true); (true will change object to array and it will be better to access it) like this and access it like in array echo $data[69]['passenger_vehicle_lanes']['maximum_lanes'].'<br>';

Related

PHP file_get_contents not showing url link

I'm having an issue with php file_get_content(), I have a txt file with links where I created a foreach loop that display multiple links in the same webpage but it's not working, please take a look at the code:
<?php
$urls = file("links.txt");
foreach($urls as $url) {
file_get_contents($url);
echo $url;
}
The content of links.txt is: https://www.google.com
Result: Only a String displaying "https://www.google.com"
Another code that works is :
$url1 = file_get_contents('https://google.com');
echo $url1;
This code returns google's homepage, but I need to use first method with loops to provide multiple links.
Any idea?
Here's one way of combining the things you already had implemented:
$urls = file("links.txt");
foreach($urls as $url) {
$contents = file_get_contents($url);
echo $contents;
}
Both file and file_get_contents are functions that return some value; what you had to do is putting return value of the latter one inside a variable, then outputting that variable with echo.
In fact, you didn't even need to use variable: this...
$urls = file("links.txt");
foreach($urls as $url) {
echo file_get_contents($url);
}
... should have been sufficient too.

Get info form phpdom

I am trying to get information using curl.
Approximately I got all information, but I need to get information individually.
For example I am getting a td text using curl.
here is the td content
jsfiddle
I need to extract text "my info", myinfo href link and last page number.
How i can do this?
here is my code which i am using in curl
$nodes = $finder->evaluate('//td[contains(text(), "") and starts-with(#id, "td_threadtitle_") ]');
foreach ($nodes as $node)
{
$innerHTML = trim($tmp_dom->saveHTML());
$fh = fopen("test.html", 'w'); // we create the file, notice the 'w'. This is to be able to write to the file once.
//writing response in newly created file
fwrite($fh, $node->c14n()); // here we write the data to the file.
fclose($fh);
}
My info
(//td[starts-with(#id, "td_threadtitle_") ]//a[1]/text())[1]
It's href
(//td[starts-with(#id, "td_threadtitle_") ]//a)[1]/#href
Last page number
substring-after(//td[starts-with(#id, "td_threadtitle_") ]//a[. = "Last Page"]/#href, "page=")
I tried this and it's according to my requirement.
Please tell me is this ok or not?
$options = $node->getElementsByTagName('a');
$post_message_id=$node->getAttribute('id');
foreach($options as $option) {
$value = $option->getAttribute('id');
if($value!=""){
print_r( $option->getAttribute('href'));
echo "\n";
print_r( $option->textContent);
echo "\n";
print_r($options->item(($options->length)-1)->getAttribute('href'));
echo "\n";
}
}

Object of std:: class cannot be converted to string

Below is a sample json code that I want to access...This json is actually coming from an API. Whenever I copy and paste the entire json in json lint..It says valid json..
foreach ($movies as $movie) {
echo "theaters ".var_dump($movie->release_dates->theater)";
}
//Im actually trying to access a nested json in php... Something like
{
"movies":[{
"tile":"Cowboys";
"release_dates":{"theater":"2013-11-29"},
so on....
Whenever I try to write the above it gives me an error Object of stdclass cannot be converted to string ....Or if I write
$x = json_decode(var_dump($movie->release_dates->theater), true)";
echo "theaters "$x[0];
It gives an output like string[10]:2013-11-25 string[10]:2013-11-30....So on..What is the error....
$data = json_decode($movies, true);
foreach ($data as $movie) {
echo "theaters ".implode(', ', $movie->release_dates->theater)";
}

Formatting XML in to JSON with PHP

I am attempting to get a JSON feed output from attributes of an XML feed. I can get the data out of the XML, however, I am unable to get it to format correctly. The error seems to be with the json_encode not adding the curly braces to the outputted date. This is the code I have so far:
<?php
$url = 'http://cloud.tfl.gov.uk/TrackerNet/LineStatus';
if(!$xml = simplexml_load_file($url))
{
die("No xml for you");
}
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
echo $line->Line['Name'];
echo $line->Status['Description'];
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));
?>
The problem is that you're not storing the name and description into the array.
Try this:
foreach ($xml->LineStatus as $line)
{
$linestatus[] = array('name' => $line->Line['Name']);
$linestatus[] = array('description' => $line->Line['Description']);
}
Demo!
The echos are screwing everything up. I think you intend to append to linestatus which remains empty per your code.
$linestatus[] = array(
"name" => $line->Line['Name'],
"description" => $line->Status['Description']
);
You also need to use echo instead of print_r to actually emit the JSON.
You are declaring $linestatus as an array, then never put anything in it before finally encoding it and trying to output it. Of course it won't work as expected! Instead, you should be populating it with values:
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
$linestatus[] = $line->Line;
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));

PHP SimpleXML Breaking when trying to traverse nodes

I'm trying to read the xml information that tumblr provides to create a kind of news feed off the tumblr, but I'm very stuck.
<?php
$request_url = 'http://candybrie.tumblr.com/api/read?type=post&start=0&num=5&type=text';
$xml = simplexml_load_file($request_url);
if (!$xml)
{
exit('Failed to retrieve data.');
}
else
{
foreach ($xml->posts[0] AS $post)
{
$title = $post->{'regular-title'};
$post = $post->{'regular-body'};
$small_post = substr($post,0,320);
echo .$title.;
echo '<p>'.$small_post.'</p>';
}
}
?>
Which always breaks as soon as it tries to go through the nodes. So basically "tumblr->posts;....ect" is displayed on my html page.
I've tried saving the information as a local xml file. I've tried using different ways to create the simplexml object, like loading it as a string (probably a silly idea). I double checked that my webhosting was running PHP5. So basically, I'm stuck on why this wouldn't be working.
EDIT: Ok I tried changing from where I started (back to the original way it was, starting from tumblr was just another (actually silly) way to try to fix it. It still breaks right after the first ->, so displays "posts[0] AS $post....ect" on screen.
This is the first thing I've ever done in PHP so there might be something obvious that I should have set up beforehand or something. I don't know and couldn't find anything like that though.
This should work :
<?php
$request_url = 'http://candybrie.tumblr.com/api/read?type=post&start=0&num=5&type=text';
$xml = simplexml_load_file($request_url);
if ( !$xml ){
exit('Failed to retrieve data.');
}else{
foreach ( $xml->posts[0] AS $post){
$title = $post->{'regular-title'};
$post = $post->{'regular-body'};
$small_post = substr($post,0,320);
echo $title;
echo '<p>'.$small_post.'</p>';
echo '<hr>';
}
}
First thing in you code is that you used root element that should not be used.
<?php
$request_url = 'http://candybrie.tumblr.com/api/read?type=post&start=0&num=5&type=text';
$xml = simplexml_load_file($request_url);
if (!$xml)
{
exit('Failed to retrieve data.');
}
else
{
foreach ($xml->posts->post as $post)
{
$title = $post->{'regular-title'};
$post = $post->{'regular-body'};
$small_post = substr($post,0,320);
echo .$title.;
echo '<p>'.$small_post.'</p>';
}
}
?>
$xml->posts returns you the posts nodes, so if you want to iterate the post nodes you should try $xml->posts->post, which gives you the ability to iterate through the post nodes inside the first posts node.
Also as Needhi pointed out you shouldn't pass through the root node (tumblr), because $xml represents itself the root node. (So I fixed my answer).

Categories