echo out just first foreach array - php

I am using this piece of code with using Simple Html dom :
$google = "http://www.google.com/something.";
$html = file_get_html($google_html);
foreach ($html->find('span[class=st]') as $element)
echo $element->innertext;
But i just want to echo out the first one of $element->innertext.
How can i just echo out first one ?
The above code echo's all elements.
Is there any way to stop the searching of simpledom , when the first child of array get found ?
I mean we don't need to get ALL of the elements, we just need the first one, so it's wasting time to picking all elements and them picking up the first one !
the Better is that when the fist one , got found , the SimpleDom get stop for finding new items.

Don't use iteration if you don't need it.
$elements = $html->find('span[class=st]');
echo $elements[0]->innertext;
You can also use the :first modifier in the selector to make it more efficient.

Use break() after the first iteration.
foreach ($html->find('span[class=st]') as $element){
echo $element->innertext;
break;
}
You can read more about break() in this documentation from PHP.net: http://php.net/manual/en/control-structures.break.php
But I'd use this method to get the first element of the array instead:
echo $html->find('span[class=st]')->innertext;
No need to loop.

Related

take one in foreach loop instead of all

I use the code below to iterate all div's on a page with id = news using PHPScraper. Is it possible to only take the first div it find so that the array only contains one entry? I was thinking of maybe (if possible) only take one in the foreach loop like you can do in c# (myList.Take(1))
$dom = file_get_html('http://localhost/test.html');
//collect all news entries into an array
$myArray = array();
if(!empty($dom)) {
$divClass = $title = '';
foreach($dom->find("div[id*=news]") as $divClass) {
You can use break to stop the loop from continuing after you've added the first div.
Something like this:
foreach($dom->find("div[id*=news]") as $divClass) {
$myArray[] = $divClass; // Just assuming you're doing something like this
break;
}
Side note: The code $divClass = $title = ''; before the loop doesn't serve any purpose in your posted code. The variable $divClass will be completely overwritten on each iteration of your foreach.
I'm guessing you're using PHP Simple HTML DOM Parser.
To grab only one element, you can simply pass 0 as the second argument of find:
$firstDiv = $dom->find('div[id*=news]', 0);
foreach($dom->find("div[id*=news]") as $divClass) {
/// work here
break;
}
break; statement is used to stop loop from further processing. So if you use it directly then loop would only execute once.

PHP Loop for, and simplexml_load_file

How can I use a loop for with simplexml_load_file to get all data?
$meteo = simplexml_load_file('hxxp://dzmeteo.com/weather.xml');
for($i=1;$i<$jours;$i++) {
$d1_icon_d = $meteo->dayf->day[$i]->part[0]->icon;
$d1_icon_n = $meteo->dayf->day[$i]->part[1]->icon;
echo $d1_icon_d;
$i++;
}
You are quite close:
$meteo = simplexml_load_file('hxxp://dzmeteo.com/weather.xml');
foreach ($meteo->dayf->day as $day) {
$d1_icon_d = $day->part[0]->icon;
$d1_icon_n = $day->part[1]->icon;
echo $d1_icon_d;
}
Any time you want to access the content on an entire array use foreach. It provides for a reliable way to ensure you have actually seen all the elements of the array and makes your code readable to yourself and others.
Remove $i++; at the end of the loop. The for loop will increment the index for you so as of now you are getting rows 1,3,5,7 and so on instead of 1,2,3,4,5,6. Also I'm not sure if this is deliberate but typically indexes start at 0 and yours starts at 1.

PHP JSON foreach Array Issue

I'm trying to use PHP to display some JSON data from an API. I need to use foreach to return all my results but nested within them is an array. The array is "highlights" which sometimes has "description" and sometimes "content" and sometimes both. I need to do a foreach within a foreach or something along those lines but everything I try just returns "Array".
Here's the JSON...
https://api.data.gov/gsa/fbopen/v0/opps?q=lte+test+bed+system&data_source=FBO&limit=100&show_closed=true&api_key=CTrs3pcYimTdR4WKn50aI1GcUxyL9M4s1fyBbSer
Here's my PHP...
$json_returned = file_get_contents("JSON_URL");
$decoded_results = json_decode($json_returned, true);
echo "Number Found:".$decoded_results['numFound']."</br> ";
echo "Start:".$decoded_results['start']."</br>";
echo "Max Score:".$decoded_results['maxScore']."</br>";
foreach($decoded_results['docs'] as $results){
echo "Parent Link T:".$results['parent_link_t']."</br>";
echo "Description:".$results['highlights']['description']."</br>";
}
Obviously the working version I'm using has a lot more fields programmed in but I cut them out to keep this code short and simple and show how I have everything else besides the "hightlights" field in one foreach. The JSON returns require that I keep everything in that foreach, so how to I display the array inside of it?
Thanks for any help and thanks for taking the time to read this even if you can contribute.
The 'description' is array with one element so you can use this.
echo 'Description:' . $results['highlights']['description'][0];
If it sometimes has 'description' and sometimes 'content'. Use isset to check which one it is, or even if there are both and print accordingly.
// for description
if(isset($results['highlights']['description'])) {
echo 'Description:' . $results['highlights']['description'][0];
}
// for content
if(isset($results['highlights']['content'])) {
echo 'Content:' . $results['highlights']['content'][0];
}
Hope this helps.
Look into the php array_column() function: http://php.net/manual/de/function.array-column.php

Returning string value in php array

Its a simple problem but i dont remember how to solve it
i have this array:
$this->name = array('Daniel','Leinad','Leonard');
So i make a foreach on it, to return an array
foreach ($this->name as $names){
echo $names[0];
}
It returns
DLL
It returns the first letter from my strings in array.I would like to return the first value that is 'Daniel'
try this one :
foreach ($this->name as $names){
echo $names; //Daniel in first iteration
// echo $names[0]; will print 'D' in first iteration which is first character of 'Daniel'
}
echo $this->name[0];// gives only 'Daniel' which is the first value of array
Inside your loop, each entry in $this->name is now $names. So if you use echo $names; inside the loop, you'll print each name in turn. To get the first item in the array, instead of the loop use $this->name[0].
Edit: Maybe it makes sense to use more descriptive names for your variables.
For example $this->names_array and foreach ( $this->names_array as $current_name ) makes it clearer what you are doing.
Additional answer concerning your results :
You're getting the first letters of all entries, actually, because using a string as an array, like you do, allows you to browse its characters. In your case, character 0.
Use your iterative element to get the complete string everytime, the alias you created after as.
If you only want the first element, do use a browsing loop, just do $this->name[0]. Some references :
http://php.net/manual/fr/control-structures.foreach.php
http://us1.php.net/manual/fr/language.types.array.php

Simple html dom - all tr except the first one

I would like to find all <tr> starting from the second, but i don't know how to get it right..
$items = $html->find('tr');
That piece of code gets all trs but i want everyone except the first one because that one contains <th>.
Just cut off the first element.
$items = array_slice($html->find('tr'), 1)
When you get your list with $html->find('tr'); make a loop that don't care of the first "index/row".
if Simple html dom work like Jquery, try to use like this:
$items = $html->find('tr:not(:has(th)');
As PoulsQ suggests you CAN do it like
$firstTr = true;
foreach($html->find('tr') as $tr) {
if(!$firstTr) {
// YOUR LOGIC FOR A TR HERE
}
else {
$firstTr = false;
}
}
But I think it would be nicer code if you query the DOM to ignore the first element.
You can get all trs from $html->find('tr'); from this u can add the condition to ignore the if the next element for object is "th" tag then u can ignore that tr.

Categories