adding data to php array within a loop - php

I am parsing data from a website via xml that always changes so I do not know what data to search for, just the location. I get the data by calling upon the specific class for the data needed. Within this class that is retrieved, there are only certain things I need retrieved. So for example, I retrieve the class .candy. Now .candy corresponds to different parts on the website so let us say that candy retrieves "Cookies Chocolate gummy bear". I only want "chocolate".
My idea was to put everything into an array an array and then access it. Assume the array is called test, then I would want to access "chocolate" by $test[1];
It is not working for me (says array is out of bounds whenever I put a number bigger than 0) and I was wondering if anyone knows where my mistake is within my code? Please note that the above was purely an example for better understanding and not the actually data I need.
Thank you
function getData($html)
{
#$doc=new DOMDocument();
#$doc->loadHTML($html);
$xml=simplexml_import_dom($doc); // just to make xpath more simple
//$images=$xml->xpath('//[]');
$info=$xml->xpath('//*[#class="date"]');
$arr= array();
foreach ($info as $img) {
$arr= array($img);
}
return $arr[3];
}

You are replacing $arr in every loop. $arr[] = $img; should work.
Example:
function getData($html)
{
#$doc = new DOMDocument();
#$doc->loadHTML($html);
$xml = simplexml_import_dom($doc);
$info = $xml->xpath('//*[#class="date"]');
$arr = array();
foreach ($info as $img)
{
$arr[] = $img;
}
return $arr[3];
}

foreach ($info as $img) {
$arr[] = $img;
}

Related

How to manually iterate over array/object without `foreach` and without `for` with PHP

There is this library https://github.com/halaxa/json-machine (PHP) that allows me to read huge JSON files without loading the entire file to memory. It works great and the way I read the JSON is like this:
$temp = \JsonMachine\JsonMachine::fromFile("teste.json");
foreach ($temp as $key => $value) {
echo $value;
}
The problem is that I cant use foreach, I need to only read the JSON as I need. For example, I tried the code below everytime I need to retrieve an element from the array:
echo next($temp);
However it returns and empty string. If I use var_dump(current($temp)) it returns this:
object(JsonMachine\StreamBytes)#2 (1) { ["stream":"JsonMachine\StreamBytes":private]=> resource(10) of type (stream) }
Using the foreach loop works perfectly, but I cant use it, I need to retrieve the elements as I need. How can I do that?
This class already provides a generator, you should be able to do something like this:
$temp = \JsonMachine\JsonMachine::fromFile("teste.json");
$iterator = $temp->getIterator();
$firstItem = $iterator->current();
$iterator->next();
$secondItem = $iterator->current();
$iterator->next();
$thirdItem = $iterator->current();
[Edit] Looks like JsonMachine::getIterator() returns a chained generator, so just change that second line to this:
$iterator = $temp->getIterator()->getIterator();

Printing multiple websites arrays

Unfortunately, after research I still couldn't find the answer for my issue.
The issue is that I cannot print data from multiple pages. Data is printed only once. Perhaps I am missing silly mistake here, which you could help me find it.
$cycles=10;
$listValue=0;
for ($cy = 0; $cy < $cycles; $cy++){
$html = file_get_contents("http://www.website.com/rate/today.aspx?d=02.03.2015&r=". $listValue ."01&c=#");
$dom = new DOMDocument;
#$dom->loadHTML($html);
$tables = $dom->getElementsByTagName('td');
$data = array();
while($table = $tables->item($i++))
{
//stuff
}
foreach($data as $item)
{
echo "Rank - " . $item['rank'] . "</br>";
}
$listValue++;
echo $listValue."<br>";
}
So basically, I am able to print data only of first page.
Declare the collection variable before the first loop $whatWasCollected = "";
Assign the collected data to a variable at the end of the first loop & Append to the variable each time.
$whatWasCollected .= "This is what I want to print..."
Get rid of the last loop and just echo the complete string.
echo $whatWasCollected;
Just a suggestion. Try it out and let me know if it works seem like and interesting question to me.

PHP: String in json parse

I am trying to parse a json. I am running this in a foreach loop and if I do the following it works:
$places = array('restaurant', 'store', 'etc')
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
However, when I do the following, i.e. I change restaurant to $places (I need to do this since I have an array of different places and I want to parse all of them in a foreach loop) it doesn't work.
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->$places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->$places[0]->geometry->location->lng;
}
Solution is changing $places to {$places}[0]
The $places array contains keywords, such as restaurant or store. So the [0] is referring to the first one in the json which is why it's needed.
Why do you have this in the first loop:
json[0]->restaurant[0]
json[0]->$restaurant[0]
But then in the next you have:
json[0]->$places[0]
json[0]->$places[0]
Perhaps you are parsing the JSON incorrectly and it should be:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->places[0]->geometry->location->lng;
}
And then in the first loop, you should do a similar edit to get rid of $restaurant[0]:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
Then again, unclear on what value $places has when you loop via foreach ($this->placesCachingTypes as $places) {. It does’t make sense what you would be looping through with the value of $places. And perhaps assigning that $places in the loop object of $json_decoded->json[0]-> is the source of your issues? Need more info from you to confirm this.

PHP Echo XML Attributes Without Repeating

my question has to do with PHP and XML. I would like to echo out some attributes, but echo ones that repeat only once.
Say this was the XML I was dealing with, and it was called beatles.xml:
<XML_DATA item=“TheBeatles”>
<Beatles>
<Beatle Firstname=“George” Lastname=“Harrison” Instrument=“Guitar”>Harrison, George</Beatle>
<Beatle Firstname=“John” Lastname=“Lennon” Instrument=“Guitar”>Lennon, John</Beatle>
<Beatle Firstname=“Paul” Lastname=“McCartney” Instrument=“Bass”>McCartney, Paul</Beatle>
<Beatle Firstname=“Ringo” Lastname=“Starr” Instrument=“Drums”>Starr, Ringo</Beatle>
</Beatles>
</XML_DATA>
This is the PHP I have so far:
$xml = simplexml_load_file("http://www.example.com/beatles.xml");
$beatles = $xml->Beatles->Beatle;
foreach($beatles as $beatle) {
echo $beatle->attributes()->Instrument.',';
}
I would expect this to echo out Guitar,Guitar,Bass,Drums, but I would like Guitar to only display once. How would I prevent repeat attribute values from echoing out?
Inside the foreach loop, cast the instrument name as a string and push it into an array. Once the loop finishes execution, you will have an array containing all the instrument names (with duplicates, of course). You can now use array_unique() to filter out the duplicate values from the array:
$instruments = array();
foreach($beatles as $beatle) {
$instruments[] = (string) $beatle->attributes()->Instrument;
}
$instruments = array_unique($instruments);
Demo.
$xml = simplexml_load_file("http://www.example.com/beatles.xml");
$beatles = $xml->Beatles->Beatle;
$result = array();
foreach($beatles as $beatle) {
if (!array_key_exists($beatle->attributes()->Instrument, $result)) {
$result[] = $beatle->attributes()->Instrument;
// echo $beatle->attributes()->Instrument.',';
}
}
then Loop through the $result array with foreach
Either use xpath.

ForEach Random Array

I'm trying to make a script that redirects to a random YouTube video. How would I take the vidKey, put each $vidkey in an array and then randomize that array so you get redirected to a different YouTube video?
$sxml = simplexml_load_file("http://gdata.youtube.com/feeds/api/users/TechTubeCentral/uploads?max-results=25");
foreach ($sxml->entry as $entry) {
$vidKey = substr(strrchr($entry->id,'/'),1);
}
Put each key into an array, then shuffle it when you're done:
$sxml = simplexml_load_file("http://gdata.youtube.com/feeds/api/users/TechTubeCentral/uploads?max-results=25");
$vidKeys = array();
foreach ($sxml->entry as $entry)
$vidKeys[] = substr(strrchr($entry->id,'/'),1);
shuffle($vidKeys);
Then just pick one entry from it, like $vidKeys[0].
You could also put the results in the database and ORDER BY RAND(). On next request you get the video keys from the DB, select and remove an entry from the list (see array_shift) and put the list back in the DB. You do this until there are no more video keys, then fire the google query again and so on... This saves your script from querying Google on each page load, and decreases the chances for being redirected to the same video
$i=0; $random_video = mt_rand(1, 25);
$sxml = simplexml_load_file("http://gdata.youtube.com/feeds/api/users/TechTubeCentral/uploads?max-results=25");
foreach ($sxml->entry as $entry) {
if($random_video==$i++){
$vidKey = substr(strrchr($entry->id,'/'),1); break;
}
}
PHP has a built-in function for selecting a random element (or elements) from an array, array_rand()
$sxml = simplexml_load_file("http://gdata.youtube.com/feeds/api/users/TechTubeCentral/uploads?max-results=25");
$vidKeys = array();
foreach ($sxml->entry as $entry)
$vidKeys[] = substr(strrchr($entry->id,'/'),1);
$randomVidKey = $vidKeys[array_rand($vidKeys)];

Categories