Array to String Conversion Error while tweaking Simplepie - php

I am using SimplePie library for feed generation. I made some changes for desired output. It was working great till today.
Here is my code:
<?php
header('Content-type: text/plain; charset=utf-8');
// Include the SimplePie library
// For 1.0-1.2:
#require_once('simplepie.inc');
// For 1.3+:
require_once('autoloader.php');
// Create a new SimplePie object
$feed = new SimplePie();
// Instead of only passing in one feed url, we'll pass in an array of three
$feed->set_feed_url(array(
'http://localhost/full-text-rss/makefulltextfeed.php?url=dynamic.feedsportal.com%2Fpf%2F555218%2Fhttp%3A%2F%2Ftoi.timesofindia.indiatimes.com%2Frssfeedstopstories.cms&key=1&hash=759dbac5d2121d4b7bc31ee9119d65a44a73fb6d&max=10&links=preserve&exc=1&format=json'
));
//Caching is enabled
$feed->enable_cache(true);
//timeout
$feed->set_timeout(40);
// We'll use favicon caching here (Optional)
//$feed->set_favicon_handler('handler_image.php');
// Initialize the feed object
$feed->init();
// This will work if all of the feeds accept the same settings.
$feed->handle_content_type();
if ($feed->error)
{
echo $feed->error;
}
$newspaperName = array('Google News');
$i = 0;
$j = 0;
$response = array();
$response["NewsItems"] = array();
foreach ($feed->get_items() as $item)
{
$feed = $item->get_feed();
//$permalink =
//$NewsItems["Count"] = html_entity_decode($feed,ENT_QUOTES, "UTF-8");//html_entity_decode($item->get_id(),ENT_QUOTES, "UTF-8");
$NewsItems["ArticleLink"] = html_entity_decode($item->get_permalink(),ENT_QUOTES, "UTF-8");//$permalink;
$NewsItems["Title"] = html_entity_decode($item->get_title(), ENT_XHTML, "UTF-8");
$NewsItems["Content"]= html_entity_decode($item->get_content(), ENT_XHTML, "UTF-8");
if($i==10)
{
$i = 0;
$NewsItems["Source"] = html_entity_decode($newspaperName[$j+1],ENT_QUOTES, "UTF-8");
$j++;
}
else
{
$NewsItems["Source"] = html_entity_decode($newspaperName[$j],ENT_QUOTES, "UTF-8");;
$i++;
}
$feed = $item->get_feed();
$NewsItems["SourceLink"]= html_entity_decode($feed->get_permalink(), ENT_XHTML, "UTF-8");
$feed = $item->get_feed();
$NewsItems["SourceTitle"] = html_entity_decode($feed->get_title(), ENT_XHTML, "UTF-8");
$NewsItems["Date"]= html_entity_decode($item->get_date('j M Y | g:i a T'), ENT_XHTML, "UTF-8");
array_push($response["NewsItems"], $NewsItems);
}
echo json_encode($response);
?>
But Today suddenly I got an error:
Notice: Array to string conversion in C:\xampp\htdocs\simplepie\IndiaEnglishTopStories.php on line 38
Array{"NewsItems":[]}
Line 38 is:
echo $feed->error;
I am not a php developer so my knowledge is very much limited. I read so many answer here and I tried to implement that but still problem is there. Forgive me if you find this question stupid and annoying. Thank you for your time.

Your trying to echo a array this is not possible. $feed->error is an array.
Change to
foreach($feed->error as $err)
echo $err;
or
var_dump($feed->error)
or
print_r($feed->error)
How to echo or print an array in PHP?

Related

SimpleXML - fails loading some remote URL's

I'm using SimpleXML to fetch a remote XML file and im having some issues because sometimes SimpleXML can't load the XML. I don't know exactly the reason but i suspect the remote site takes longer than usual to return data, resulting in a timeout.
The code i use is the following:
$xml = #simplexml_load_file($url);
if(!$xml){
$database = Config_helper::get_config_option('mysql');
$db = new \DB($database['database'], $database['server'], $database['user'], $database['password']);
$date = date('Y-m-d H:i:s');
$db->query("INSERT INTO gearman_job_error (timestamp, data, attempt)
VALUES ('$date', '{$job->workload()}', '1')");
//$db->query("INSERT INTO gearman_job_error (timestamp, data, attempt) VALUES ({$date}, {$job->workload()}, 1);");
return $job->sendFail();
}
else {
foreach($xml->point as $key=>$value):
$length = count($value);
$timestamp = (string) $value->data[0];
$j=0;
for ($i = 1; $i < $length; $i++)
{
$forecast[$timestamp][$time_request][] = array($variables[$j] => (string) $value->data[$i]);
$j++;
}
endforeach;
return serialize($forecast);
}
Those url's i can't load are stored in the database and by checking them i confirm that they load correctly in the browser.. no problem with them.
Example: http://mandeo.meteogalicia.es/thredds/ncss/modelos/WRF_HIST/d02/2015/02/wrf_arw_det_history_d02_20150211_0000.nc4?latitude=40.393288&longitude=-8.873433&var=rh%2Ctemp%2Cswflx%2Ccfh%2Ccfl%2Ccfm%2Ccft&point=true&accept=xml&time_start=2015-02-11T00%3A00Z&time_end=2015-02-14T20%3A00Z
My question is, how can i insist the SimpleXML to take it's time to load the url? My goal is only after a reasonable time it assumes it can't load the file and store it in the database.
simplexml_load_file itself doesn't have any support for specifying timeouts, but you can combine file_get_contents and simplexml_load_string, like this:
<?php
$timeout = 30;
$url = 'http://...';
$context = stream_context_create(['http' => ['timeout' => $timeout]]);
$data = file_get_contents($url, false, $context);
$xml = simplexml_load_string($data);
print_r($xml);
I figured a way of doing this that for now suits me.
I set a maximum number of tries to fetch the xml and if it doesn't work that means the xml can be possibly damaged or missing.
I have tested and the results are accurate! It's simple and more effective then setting a timeout. I guess you can always set a timeout also.
$maxTries = 5;
do
{
$content = #file_get_contents($url);
}
while(!$content && --$maxTries);
if($content)
{
try
{
$xml = #simplexml_load_string($content);
# Do what you have to do here #
}
catch(Exception $exception)
{
print($exception->getMessage());
}
}
else
{
echo $url;
$job->sendFail();
}

PHP creating multiple DOMDocuments in a loop issue

I have a list of items to be added to the end of a base url and am trying to retrieve the html from each of these generated url's in a loop. However, I am encountering an error and i've really been struggling to fix it!
current code:
($items is just an array of strings)
$output = "";
foreach($items as $item) {
$url = $baseUrl . $item;
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTMLFile($url);
$output = $output . json_encode($dom->saveHTML());
}
echo $output;
Can anyone tell me why I can't load multiple HTML documents like this?
Annoyingly i'm not getting any PHP error logs and the ajax xhr text is not providing any useful info, it's just returning a section of the first html page loaded as the 'error' (it seems to be able to load the first item in the array but then fails)
You were almost there. This way it should do the trick:
$output = "";
foreach($items as $item) {
$url = $baseUrl . $item;
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTMLFile($url);
$output .= json_encode($dom->saveHTML(),JSON_ERROR_UTF8);
}
echo $output;

How to conect php with tally?

I want to connect php with tally and I want to store ledger in tally with php any idea?
I got reference from different site like :
1) http://www.tallysolutions.com/website/html/tallydeveloper/integration-capabilities.php
2)http://stackoverflow.com/questions/15717941/how-to-insert-data-into-tally-using-php
But it doesn't fulfill my requirement.
Thanks in advance
It's may help you
// create a new XML document
$doc = new DomDocument('1.0', 'UTF-8');
$envelope = $doc->appendChild($doc->createElement('ENVELOPE'));
//Header Section
$header = $envelope->appendChild($doc->createElement('HEADER'));
$version = $header->appendChild($doc->createElement('VERSION','6.3'));
$import = $header->appendChild($doc->createElement('TALLYREQUEST','Import'));
$type = $header->appendChild($doc->createElement('TYPE','Data'));
$id = $header->appendChild($doc->createElement('ID','All Masters'));
//End Header Section
//Body Section
$body = $envelope->appendChild($doc->createElement('BODY'));
$desc = $body->appendChild($doc->createElement('DESC'));
$static_var = $desc->appendChild($doc->createElement('STATICVARIABLES'));
$dup_combine = $static_var->appendChild($doc->createElement('IMPORTDUPS','##DUPCOMBINE'));
$data = $body->appendChild($doc->createElement('DATA'));
$tally_msg = $data->appendChild($doc->createElement('TALLYMESSAGE'));
//Ledger Data
foreach($contacts_data as $key => $value){
$ledger = $tally_msg->appendChild($doc->createElement('LEDGER'));
$parent=$ledger->appendChild($doc->createElement('PARENT',($value['contacts_types_id']=='1')?'Sundry Debtors':'Sundry Creditors'));
$name=$ledger->appendChild($doc->createElement('NAME',trim(str_replace( "&"," AND ",$value['name']))));
$address=$ledger->appendChild($doc->createElement('ADDRESS',trim(str_replace( "&"," AND ",$value['address']))));
$state=$ledger->appendChild($doc->createElement('STATENAME',trim(str_replace( "&"," AND ",$value['state_name']))));
$pincode=$ledger->appendChild($doc->createElement('PINCODE',$value['pincode']));
/*$ledger_contact=$ledger->appendChild($doc->createElement('LEDGERCONTACT',trim(str_replace( "&"," AND ",$value['contact_person']))));
$phone=$ledger->appendChild($doc->createElement('LEDGERPHONE',$value['phone']));
$fax=$ledger->appendChild($doc->createElement('LEDGERFAX',$value['fax']));
$mobile_no=$ledger->appendChild($doc->createElement('MOBILENO',$value['mobile_no']));
$sales_tax_no=$ledger->appendChild($doc->createElement('SALESTAXNO','23456789'));
$pan_no=$ledger->appendChild($doc->createElement('PANNO','453456789'));*/
$o['contacts_id'][]=$value['id'];
}
//End Ledger and Body Section
//Write the XML nodes
$fp = fopen(public_path()."/xml/import_tally/ledger.xml","wb");
if(fwrite($fp,$doc->saveXML())){
$o['tally_rslt']= shell_exec("curl -X POST tally_server_ip:port --data #".public_path()."/xml/import_tally/ledger.xml");
$o['modified_result']=strpos(preg_replace('/[0-9]+/', '', $o['tally_rslt']),'exists');
}
fclose($fp);
return $o;

Error while loading xml file?

Am dynamically loading an xml file and sending request to the api but getting
Warning: DOMDocument::loadXML(): Empty string supplied as input in /home/spotrech/public_html/ but this error is very inconsistent sometime appear sometime don't! I really no idea how to solve this. below is code
$rechargeApiUrl = "http://allrechargeapi.com/apirecharge.ashx?uid=$uid&apikey=$apike&number=$mobileNo&opcode=$opId&amount=$amount&ukey=$uniId&format=xml";
$url = file_get_contents($rechargeApiUrl);
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML(preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $url));
$itemInfo = $xmlDoc->getElementsByTagName('Result'); //returns an object.
$itemCount = $itemInfo->length;
foreach ($itemInfo as $userInfo) {
//Assigning node values to its specified variables.
$ukey = strtolower($userInfo->getElementsByTagName('ukey')->item(0)->childNodes->item(0)->nodeValue);
$status = $userInfo->getElementsByTagName('status')->item(0)->childNodes->item(0)->nodeValue;
$resultCode = $userInfo->getElementsByTagName('resultcode')->item(0)->childNodes->item(0)->nodeValue;
}
$strStatus = strtolower(trim($status));
$strResultCode = trim($resultCode);
$strCode = trim($ukey);
any response will be appreciated.Thank you

Fatal error: Out of memory PHP

I am not sure why this was working fine last night and this morning I am getting
Fatal error: Out of memory (allocated 1611137024) (tried to allocate
1610350592 bytes) in /home/twitcast/public_html/system/index.php on
line 121
The section of code being ran is as follows
function podcast()
{
$fetch = new server();
$fetch->connect("TCaster");
$collection = $fetch->db->shows;
// find everything in the collection
$cursor = $collection->find();
if($cursor->count() > 0)
{
$test = array();
// iterate through the results
while( $cursor->hasNext() ) {
$test[] = ($cursor->getNext());
}
$i = 0;
foreach($test as $d) {
for ( $i = 0; $i <= 3; $i ++) {
$url = $d["streams"][$i];
$xml = file_get_contents( $url );
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->loadXML( $xml); // $xml = file_get_contents( "http://www.c3carlingford.org.au/podcast/C3CiTunesFeed.xml")
// Initialize XPath
$xpath = new DOMXpath( $doc);
// Register the itunes namespace
$xpath->registerNamespace( 'itunes', 'http://www.itunes.com/dtds/podcast-1.0.dtd');
$items = $doc->getElementsByTagName('item');
foreach( $items as $item) {
$title = $xpath->query( 'title', $item)->item(0)->nodeValue;
$published = strtotime($xpath->query( 'pubDate', $item)->item(0)->nodeValue);
$author = $xpath->query( 'itunes:author', $item)->item(0)->nodeValue;
$summary = $xpath->query( 'itunes:summary', $item)->item(0)->nodeValue;
$enclosure = $xpath->query( 'enclosure', $item)->item(0);
$url = $enclosure->attributes->getNamedItem('url')->value;
$fname = basename($url);
$collection = $fetch->db->shows_episodes;
$cursorfind = $collection->find(array("internal_url"=>"http://twitcatcher.russellharrower.com/videos/$fname"));
if($cursorfind->count() < 1)
{
$copydir = "/home/twt/public_html/videos/";
$data = file_get_contents($url);
$file = fopen($copydir . $fname, "w+");
fputs($file, $data);
fclose($file);
$collection->insert(array("show_id"=> new MongoId($d["_id"]),"stream"=>$i,"episode_title"=>$title, "episode_summary"=>$summary,"published"=>$published,"internal_url"=>"http://twitcatcher.russellharrower.com/videos/$fname"));
echo "$title <br> $published <br> $summary <br> $url<br><br>\n\n";
}
}
}
}
}
line 121 is
$data = file_get_contents($url);
You want to add 1.6GB of memory usage for a single PHP thread? While you can increase the memory limit, my strong advice is to look at another way of doing what you want.
Probably the easiest solution: you can use CURL to request a byte range of the source file (using Curl is wiser than get_file_contents anyway, for remote files). You can get 100K ata time, write to the local file then got the next 100k and appeand to the file etc, until the entire file is pulled in.
You may also do something with streams, but it gets a little more complex. This may be your only option if the remote server won't let you get part of a file by bytes.
Finally there's Linux commands such as wget, run through exec(), if your server has permissions.
Memory Limit - take a look at this directive. Suppose that is what you need.
or you may try to use copy instead of reading file to memory (which is video file, as I understand so there is nothing strange that it takes a lot of memory):
$copydir = "/home/twt/public_html/videos/";
copy($url, $copydir . $fname);
Looks like last night opened file were smaller)

Categories