Why isn't PHP continuing to run through these urls? - php

I have the following PHP. Basically, I'm getting similar data from multiple pages of a website (the current number of homeruns from a website that has a bunch of baseball player profiles). The JSON that I'm bringing in has all of the URLs to all of the different profiles that I'm looking to grab from, and so I need PHP to run through the URLs and grab the data. However, the following PHP only gets the info from the very first URL. I'm probably making a stupid mistake. Can anyone see why it's not going through all the URLs?
include('simple_html_dom.php');
$json = file_get_contents("http://example.com/homeruns.json");
$elements = json_decode($json);
foreach ($elements as $element){
$html = new simple_html_dom();
$html->load_file($element->profileurl);
$currenthomeruns = $html->find('.homeruns .current',0);
echo $element->name, " currently has the following number of homeruns: ", strip_tags($currenthomeruns);
return $html;
}

Wait... You are using return $html. Why? Return is going to break out of your function, thus stopping your foreach.
If you are indeed trying to get the $html out of your function for ALL of the elements, you should push each $html into an array and then return that array after the loop.

Because you return. return leaves the current method, function, or script, which includes every loop. With PHP5.5 you can use yield to let the function behaves like an generator, but this is definitely out of scope for now.

Unless your braces are off, you return at the very end of the loop so the loop will never iterate.

Related

Using PHP SimpleXML to parse an oBix XML feed?

I am rather new to development, but a long time sys-admin. I am trying to retrieve a specific value from the following XML feed. (Its oBix).
http://80.68.58.47:900/obix/config/Drivers/NiagaraNetwork/OSS_Tridium_Demo/points/kW_Sys/
I am trying to return the "Out" value within the 'Real' element (If element is the right name for it). The value is a number next to val=.
I have spent a fair few hours trying to work out how to isolate the 'val' attribute and return the number but I can't seem to do it. I can isolate the 'real' element but can't go any further in to get the actual number value.
Could someone show me how this is done using PHP SimpleXML so I can try to get my head round it?
This is my code so far:
<?php
$url = "http://80.68.58.47:900/obix/config/Drivers/NiagaraNetwork/OSS_Tridium_Demo/points/kW_Sys/";
$xml = simplexml_load_file($url);
$elementselection = $xml->real[0];
$outputvalue = $elementselection;
print_r ($outputvalue);
?>
Many Thanks!
Tom
If you just want the value from the first 'real' element you can use the following:
$url = "http://80.68.58.47:900/obix/config/Drivers/NiagaraNetwork/OSS_Tridium_Demo/points/kW_Sys/";
$xml = simplexml_load_file($url);
$value = (string) $xml->real[0]['val'];
var_dump($value);

Searching for a link in a website and displaying it PHP

hello im a newbie in php i am trying make a search function using php but only inside the website without any database
basically if i want to search a string namely "Health" it would display the lines
The Joys of Health
Healthy Diets
This snippet is the only thing i could find if properly coded would output the "lines" i want
$myPage = array("directory.php","pages.php");
$lines = file($myPage[n]);
echo $lines[n];
i havent tried it yet if it would work but before i do i want to ask if there is any better way to do this?
if my files have too many lines wont it stress out the server?
The file() function will return an array. You should use file_get_contents() instead, as it returns a string.
Then, use regular expressions to find specific text within a link.
Your goal is fine but the method you're thinking about is not. the file() function read a file, line by line, and inserts it into an array. This assumes the HTML is well-structured in a human-readable fashion, which is not always the case. However, if you're the one providing the HTML and you make sure the structure is perfectly defined, ok... here you have the example you provided us with but complete (take into account it's the 'wrong' way of solving your problem, but if you want to follow that pattern, it's ok):
function pagesearch($pages, $string) {
if (!empty($pages) && !empty($string)) {
$tags = [];
foreach ($pages as $page) {
if ($lines = file($page)) {
foreach ($lines as $line) {
if (!empty($line)) {
if (mb_strpos($line, $string)) {
$tags[$page][] = $line;
}
}
}
}
}
return $tags;
}
}
This will return you an array with all the pages you referenced with all occurrences of the word you look for, separated by page. As I said, it's not the way you want to solve this, but it's a way.
Hope that helps
Because you do not want to use any database and because the term database is very broad and includes the file-system you want to do a search in some database without having a database.
That makes no sense. In your case one database at least is the file-system. If you can accept the fact that you want to search a database (here your html files) but you do not want to use a database to store anything related to the search (e.g. some index or cached results), then what you suggest is basically how it is working: A real-time, text-based, line-by-line file-search.
Sure it is very rudimentary but as your constraint is "no database", you have already found the only possible way. And yes it will stress your server when used because real-time search is expensive.
Otherwise normally Lucene/Solr is used for the job but that is a database and a server even.

PHP code inside MYSQL table does not show

I am trying to convert a drupal installation into a front end driven by Code Igniter. This is an experimental project to check the performance boost I can get. But the biggest problem I am facing is that few fields in Drupal store php string as it is. For example
<?php print "A"; ?>
This is normal
Now I am able to see the text "This is normal" which comes from the query that I run in Code Igniter, but I don't see the php function which is saved inside the table. I can see the text when I view the record through phpmyadmin. But somehow not inside the CI query result.
I hope U've got the solution. But just in case if you haven't try this:
I created a table with two columns
//$result Contains the data fetched from the table using a model.
foreach ($result as $key=>$val) {
if($key == 'code') {
$val = str_replace('<?php','',$val); //Remove PHP's opening tag.
$val = str_replace('?>','',$val); //Remove PHP's closing tag.
$val = rtrim($val); //Remove leading and trailing spaces.
echo $key.': ';
eval($val.';'); //Execute the PHP code using eval.
} else {
echo $key.': '.$val.PHP_EOL;
}
}
I tried
echo $result['code']
print_r($result)
var_dump($result)
highlight_string($result['code'])
eval($result['code'])
and finally str_replace followed by eval($result['code']).
Check the screen shot of the result obtained from: here
There you can see that the Result produced by 1,2, and 5 are empty. But when you inspect element against the empty space It'll clearly show that the string that's echoed/print is commented out.
Screen-Shot. This is has nothing to do with codeigniter. Its done by HTML Parser.
So the solution is to remove the opening and closing tags of PHP and then use eval. I hope this helps.
Thanks for the help. Yes, the last resort was the eval function and that is the one which helped me attain which I was wanting it to do.
The data which was inside the database had PHP function and only eval function was able to treat that part as a PHP code and execute it when I was getting the data inside my view.

Return a List of links in reddit using PHP

Just wondering if someone has sample code to return the top 25 links of reddit (using PHP). In JSON or XML. i can't wrap my head around the API... and rarely use python.
$array = (array) json_decode(file_get_contents("http://www.reddit.com/.json"));
That will return a PHP array with all the data from the front page. You can limit how many you display using a simple while() loop.
This is very simple now that you have the array from above, because all you have to do is step through it.

From select box to array

I have a series of select boxes that I'd like to get data from, essentially turning them into an array. What's the most efficient way to do this? Right now I'm thinking....
$html = file_get_contents('http://www.domain.com');
preg_match_all("/name\=\'subscription\[division_id\]\' style\=\'width: 170px;\'>(.+?)<\/select>/is", $html, $matches);
Then I was thinking of running other code to take the option tags into an array, but this seems it might be a little unnecessarily intensive
If you are scraping for whatever reason, you could probably parse the page's html with php's DOMXPath commands. I can't write out all the code, but you can get started with:
$xpath = new DOMXPath($dom);
$select_values = $xpath->evaluate("/html/body//option");
Then you run everything through a loop getting the contents of the options. Anyway, with something like this you can avoid all the nonsense with regex.

Categories