In my UI there is a text area that has a list of URLs separated by new line.
I am getting this into a string and exploding it using newline character. I am getting this error:
Fatal error: Call to a member function find() on a non-object in C:\xampp\htdocs\apps\lt\track-them.php on line 34
$myurl = "http://mydomain.com/testpage1.html";
$str = "http://www.domain.com/page1.html
http://www.homepage.com/page2.html
http://www.internet.com/index.html";
$backlinkarr = explode("\n", $str);
echo '<table border=1>';
foreach ($backlinkarr as $backlinkitem) {
$backlinkitem = trim($backlinkitem);
$LinkCount = 0;
$html = file_get_html($backlinkitem);
foreach ($html->find('a') as $link) {
if ($link->href == $myurl) {
$LinkCount += $LinkCount + 1;
}
}
echo $backlinkitem . ' (' . $linkCount . ')';
}
on windows new line is \r\n
also, your error suggests that $html is not an object, meaning previous line fails. so, debug there with var_dump($backlinkitem) if it is correct and also you can use file_exists to verify if that file actually exists.
Related
I've been trying to get further in PHP and writing functions daily to practice but started to get the feeling I'm either overcomplicating or doing it completely wrong.
My 2 functions for this script:
function getFilesAndContent($path)
{
$data = [];
$folderContents = new DirectoryIterator($path);
foreach ($folderContents as $fileInfo) {
if ($fileInfo->isDot()) {
break;
}
$fileData = [
'file_name' => $fileInfo->getName(),
];
if ($fileInfo->getExtension()) {
$fileData['contents'] = getFileContents($fileInfo->getPathname());
}
$data = $fileData;
}
return $data;
}
function getFileContents($path)
{
$names = file_get_contents($fileInfo->getPathname());
$names = implode("\n", $names);
sort($names);
$contents = '';
foreach ($names as $name) {
$contents += $name . ' (' . strlen($name) . ')<br>';
}
return $name;
}
All I want to do is:
foreach (getFilesAndContent('.') as $data) {
echo $data['file_name'];
echo '<br>';
echo $data['contents'];
echo '<hr>';
The error:
FATAL ERROR Uncaught Error: Call to undefined method DirectoryIterator::getName() in /home4/phptest/public_html/code.php70(5) : eval()'d code:15 Stack trace: #0 /home4/phptest/public_html/code.php70(5) : eval()'d code(45): getFilesAndContent('.') #1 /home4/phptest/public_html/code.php70(5): eval() #2 {main} thrown on line number 15
The file it's supposed to read is a simple .txt files with a list of names, nothing more.
Any help appreciated! Also wondering if it's better to just rewrite the entire functions if I keep getting so many errors?
You have many things to fix in your code, for example changing undefined method getName() to something else, don't use break to skip because it will exit the loop, using explode(string $separator, string $string) to split string by separator, return $contents from getFileContents() function to return final concatenated string, etc.
I think, your goal is to display all *.txt files and its contents, with length for each line in contents. Try this:
$d = dir('.');
while (($file = $d->read()) !== false) { // iterate all files
if (preg_match('/\.txt$/', $file)) { // filter only file ends with .txt
$contents = explode("\n", file_get_contents($d->path . '/' . $file)); // get file contents, split by \n
array_walk($contents, function(&$item) {
$item .= ' (' . strlen($item) . ')';
}); // add (length) in the end of each line
// display it
echo '<strong>' . $file . '</strong><br>';
echo implode('<br>', $contents);
echo '<hr>';
}
}
I can't figure out where is mistake in this code and how to solve this error.
Error reported is:
Notice: Undefined offset: 1 in /Applications/XAMPP/xamppfiles/htdocs/bat/rd-search.php on line 53 that is this string of code:
$final_result[$file_count]['page_title'][] = $page_title[1];
the code is:
$contents = file_get_contents($file);
preg_match("/\<title\>(.*)\<\/title\>/", $contents, $page_title); //getting page title
if (preg_match("#\<body.*\>(.*)\<\/body\>#si", $contents, $body_content)) { //getting content only between <body></body> tags
$clean_content = strip_tags($body_content[0]); //remove html tags
$clean_content = preg_replace('/\s+/', ' ', $clean_content); //remove duplicate whitespaces, carriage returns, tabs, etc
$found = strpos_recursive(mb_strtolower($clean_content, 'UTF-8'), $search_term);
$final_result[$file_count]['page_title'][] = $page_title[1];
$final_result[$file_count]['file_name'][] = preg_replace("/^.{3}/", "\\1", $file);
}
for ($j = 0; $j < count($template_tokens); $j++) {
if (preg_match("/\<meta\s+name=[\'|\"]" . $template_tokens[$j] . "[\'|\"]\s+content=[\'|\"](.*)[\'|\"]\>/", $contents, $res)) {
$final_result[$file_count][$template_tokens[$j]] = $res[1];
}
}
This is because the preg_match returns no matches.
You can resolve this by adding a line below such as the following:
preg_match("/\<title\>(.*)\<\/title\>/", $contents, $page_title); //getting page title
$page_title = empty($page_title) ? [0 => '', 1 => ''] : $page_title;
This will just create an array with 0 and 1 as indexes if preg_match failed to get any matches for a title.
The other alternative is to check the value of $page_title before trying to access it. This approach means that you will have to create a check each time you want to access this variable, whereas the first approach doesn't because the indexes have blank values.
if (!empty($page_title) {
$final_result[$file_count]['page_title'][] = $page_title[1];
}
I am trying to read a link from one page, print the URL, go to that page, and read the link on the next page in the same location, print the url, go to that page (and so on...).
All I'm doing is reading the URL and passing it as an argument to the get_links() function until there are no more links.
This is my code but it throws:
Fatal error: Call to a member function find() on a non-object.
Anyone know how to fix this?
<?php
$mainPage = 'https://www.bu.edu/link/bin/uiscgi_studentlink.pl/1346752597?ModuleName=univschr.pl&SearchOptionDesc=Class+Subject&SearchOptionCd=C&KeySem=20133&ViewSem=Fall+2012&Subject=&MtgDay=&MtgTime=';
get_links($mainPage);
function get_links($url) {
$data = new simple_html_dom();
$data = file_get_html($url);
$nodes = $data->find("input[type=hidden]");
$fURL = $data->find("/html/body/form");
$firstPart = $fURL[0]->action . '<br>';
foreach ($nodes as $node) {
$val = $node->value;
$name = $node->name;
$name . '<br />';
$val . "<br />";
$str1 = $str1 . "&" . $name . "=" . $val;
}
$fixStr1 = str_replace('&College', '?College', $str1);
$fixStr2 = str_replace('Fall 2012', 'Fall+2012', $fixStr1);
$fixStr3 = str_replace('Class Subject', 'Class+Subject', $fixStr2);
$fixStr4 = $firstPart . $fixStr3;
echo $nextPageURL = chop($fixStr4);
get_links($nextPageURL);
}
?>
Alright so I was using the load->file() function somewhere in my code and did not see it until I really scraped through it. Finally have a running script :) The key is to use file_get_html instead of loading the webpage as an object using the load->file() function.
I am trying to pull text from a single element in an xml file, i was able to pull the entire file but i really only need a couple of lines from the file...
On this page i was able to pull the entire xml file ( http://smyrnainlet.com/testing.php )
But when i try to just single out one line from that file.
http://smyrnainlet.com/current_data.php
This is the error i am receiving:
Fatal error: Call to a member function getbyElementID() on a non-object in /home/content/74/8620474/html/current_data.php on line 9
If anyone could help me that would be amazing, i have been struggling with this for hours.
This is my code:
<?php
function startElemHandler($parser, $name, $attribs)
{
if (strcasecmp($name, "current_observation") ==0 ) {
echo "<div id='waves'>\n";
}
if (strcasecmp($name, "wave_height_ft") ==0) {
$waveHeight->getbyElementID("wave_height_ft");
echo $waveHeight->asXML();
}
}
function endElemHandler($parser, $name)
{
if (strcasecmp($name, "current_observation") ==0 ) {
echo "</div>";
}
}
$parser = xml_parser_create();
xml_set_element_handler($parser, startElemHandler, endElemHandler);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
$strXML = implode("",file("http://www.weather.gov/xml/current_obs/41009.xml"));
xml_parse($parser, $strXML);
xml_parser_free($parser);
?>
You have a few fundamental flaws with your code but you are essentially asking how to parse an XML file. I suggest using PHP's DOMDocument with DOMXPath to extract the data you need. Here is some example code:
$xml = file_get_contents('weather.xml');
$dom = new DOMDocument();
#$dom->loadHTML($xml);
$domx = new DOMXPath($dom);
$entries = $domx->evaluate("//wave_height_ft");
$arr = array();
foreach ($entries as $entry) {
$arr[] = '<' . $entry->tagName . '>' . $entry->nodeValue . '</' . $entry->tagName . '>';
}
print_r($arr);
$waveHeight seem not defined (not in scope) wher you try to use it!
you can
pass it as argument
use the global statement
create a class
Quite some time ago I wrote a RSS parser. It worked fine until now, when I turned my error and notice reporting on. Currently I keep getting quite a lot of notices that tell me that something is wrong in the function. I tried solving this problem on my own, but I had no success. Could You please help me with this error?
The error:
Notice: Undefined index: RSS in C:\xampp\htdocs\Dropbox\RECtus\System\sysFiles\libarys\myRSSParser.lib(103) : eval()'d code on line 1
Notice: Undefined index: LINK in C:\xampp\htdocs\Dropbox\RECtus\System\sysFiles\libarys\myRSSParser.lib(103) : eval()'d code on line 1
The script:
function parseData($parser, $data) {
if(!trim($data)) return;
$RSS = '';
$evalcode = "\$this->output";
foreach($this->tags as $tag) {
if(is_array($tag)) {
list($tagname, $indexes) = each($tag);
$evalcode .= "[\"$tagname\"]";
if(!isset(${$tagname})) ${$tagname} = '';
if(${$tagname}) $evalcode .= "[" . (${$tagname} - 1) . "]";
if($indexes) extract($indexes);
} else {
if(preg_match("/^([A-Z]+):([A-Z]+)$/", $tag, $matches)) {
$evalcode .= "[\"$matches[1]\"][\"$matches[2]\"]";
} else {
$evalcode .= "[\"$tag\"]";
}
}
}
eval("$evalcode = $evalcode . '" . addslashes($data) . "';");
}
Line 103 is the eval() line.
Why are you using eval() ?
It seems you're just trying to concatenate portions of string, no ?
If so, why not just... concatenate portions of strings ?
Basically, you should be able to do something like this :
$this->output = array();
$this->output['...'] = 'some string';
$this->output['...'] = array();
$this->output['...']['...'] = 'some other string';