xpath with curl gives empty result? - php

This code gives me an empty result. I expect it to print out the titles from the XML-file. I need to use Curl to get the file.
<?php
function get_url($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$xml_content = get_url("http://www.e24.se/?service=rss&type=latest");
$dom = new DOMDocument();
#$dom->loadXML($xml_content);
$xpath = new DomXPath($dom);
$results = $xpath->query('//channel//title/text()');
foreach ($results as $result)
{
echo $result->title . "<br />";
}
?>

I found it already. The loop is wrong. It should be...
foreach ($results as $result)
{
echo $result->nodeValue . "<br />";
}

Related

JSON array foreach loop showing Invalid argument supplied for foreach()

I want to display http://services.xyz.com/tours.asmx/Sample?type=2&CityID=1146&days=4 this array data in HTML.
Here is my code:
ini_set("display_errors", 1);
$url = "http://services.xyz.com/tours.asmx/Sample?type=2&CityID=1146&days=4";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // set the fields to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // make sure we get the response back
$xml = curl_exec($ch); // execute the post
curl_close($ch); // close our session
include "XMLParser.php";
$parser = new XMLParser();
$tour = $parser->parseString($xml);
print_r($tour);
//$errors = array_filter($tour);
if (empty($tour)) {
echo 'Error';
}else{
echo 'No Error';
}
//print_r($xml);
//var_dump( $xml);
//echo $xml;
//$xmlfile = file_get_contents($tour);
$ob= simplexml_load_string($tour);
//$json = json_encode($ob);
$configData = json_decode($ob, true);
foreach($configData as $result){
echo '<tr>';
echo '<td>'.$result->name.'</td>';
echo '<td>'.$result->phone.'</td>';
echo '<td>'.$result->email.'</td>';
echo '</tr>';
}
I am getting this error Warning: Invalid argument supplied for foreach() in C:
Please help me.
Thanks
Here is my final Working code to help someone else who need this code.
<?php
ini_set("display_errors", 1);
//$days = "http://services.xyz.com/tours.asmx/Days?type=2&cityID=1146";
$url = "http://services.xyz.com/tours.asmx/Sample?type=2&CityID=1146&days=4";//Replace this with your own Web services Link
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // make sure we get the response back
$xml = curl_exec($ch); // execute the post
curl_close($ch); // close our session
$var = simplexml_load_string($xml);
$configData = json_decode($var, true);
/*echo '<pre>';
print_r($configData);
echo '</pre>';*/
foreach ($configData as $row) {
echo 'Day:' . $row['Day'].'<br>';
echo 'Time:' .$row['Time'].'<br>';
echo 'Description:' .$row['Description'].'<br>';
}?>

"Invalid argument supplied for foreach()" reading XML?

IM gettin: "Invalid argument supplied for foreach()"
in the for each line when trying to read an specific item of the xml
PHP:
$urls="http://www.floatrates.com/daily/usd.xml";
$url= $urls;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$feed = new SimpleXMLElement($data,LIBXML_NOCDATA);
foreach ($feed->channel->item as $item) {
$title = $item->title;
if (preg_match('/ARS/',$title)) {
echo $title;
}
}
$urls = "http://www.floatrates.com/daily/usd.xml";
$url = $urls;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$feed = new SimpleXMLElement($data, LIBXML_NOCDATA);
foreach ($feed->children() as $item) {
if ("item" == $item->getName()) {
$title = $item->title;
if (preg_match('/ARS/', $title)) {
echo $title;
}
}
}
It probably means that $feed does not contain what you expect it to contain, and you are not passing array to foreach Use print_r($feed); to see that it actually contains, and go from there.

removing a "," from the last element in a foreach loop?

i am trying (like hell..) to remove ',' from the last element in a foreach loop.
tried several counter methods, but not really successfully.
[<?php
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = fetchData("https://api.instagram.com/v1/users/XXXXXXX/media/recent/?access_token=XXXXXXX&count=10");
$result = json_decode($result);
foreach ($result->data as $post) {
echo '{"name":"Hello","imgpath":" ';echo $post->images->low_resolution->url;echo '"},';
}
?>]
Use json_encode()
<?php
...
$json = array();
foreach ($result->data as $post){
$json[]=array(
'name'=>'Hello',
'imgpath'=>$post->images->low_resolution->url,
);
}
header('Content-Type: application/json');
exit(json_encode($json));
?>
Store the whole thing in a string instead of echoing it, then you can cut the last character using $string=substr($string,0,-1);
[<?php
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = fetchData("https://api.instagram.com/v1/users/XXXXXXX/media/recent/?access_token=XXXXXXX&count=10");
$string="";
$result = json_decode($result);
foreach ($result->data as $post) {
$string.='{"name":"Hello","imgpath":"' . $post->images->low_resolution->url . '"},';
}
echo substr($string,0,-1);
?>]
Maybe something like:
// quick and dirty solution
foreach ($result->data as $index => $post) {
$comma = ',';
if ((int) $index === count($result->data) -1) {
$comma = '';
}
$string.='{"name":"Hello","imgpath":" ';echo $post->images->low_resolution->url;echo '"}'.$comma;
}
I would use implode, quite cleaner:
$result = json_decode($result);
$string = '{"name":"Hello","imgpath":"';
$string .= implode( '}, {"name":"Hello","imgpath":"', $result->data );
$string .= '}';
echo $string;

How to get data from a table on a webpage in PHP

I am trying to get data from four rows each with two rows from a webpage. After some reading around I have tried the following code;
<?PHP
require('simple_html_dom.php');
$ch = curl_init();
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
$target_url = 'http://www.boz.zm/(S(0m5hxtuuoex4xqjkzrpbsh55))/Startpage.aspx';
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$html = curl_exec($ch);
if (!$html)
{
echo "<br />cURL error number:" .curl_errno($ch);
echo "<br />cURL error:" . curl_error($ch);
exit;
}
else
{
echo "<br> Think the page was nabbed";
$dom = new DOMDocument();
#$dom->loadHTML($html);
$xpath = new DOMXpath($dom);
$tableData = array();
foreach($xpath->query('//table[#id="_ctl0_zmain_Dg_ExchangeRates"]/tr[position()<5]') as $node)
{
$rowData = array();
foreach($xpath->query('td', $node) as $cell)
{
$rowdat = $cell->textContent;
$rowData[] = $rowdat;
}
$tableDate[]=$rowData;
}
print_r($tableData);
}
?>
Only returns an empty array.
I would like to put the values of each row in a multidimensional array so I can easily work with them. Any ideas on how I can achieve this task, even if its a different approach from what im trying to do I dont mind.? Thanks in Advance.
It is only a mistyping: you have written : $tableDate[]=$rowData; instead of $tableData[]=$rowData;

Problem with curl, xpath query

I need some help with my xpath query. I can get this code to work with just about every site I need to scrape except this small part of a particular site... I just get a blank page... Does anyone have an idea on how I can do this better?
//
$target_url = "http://www.teambuy.ca/vancouver/";
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
// make the cURL request to $target_url
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT,$userAgent);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html= curl_exec($ch);
if (!$html) {
echo "<br />cURL error number:" .curl_errno($ch);
echo "<br />cURL error:" . curl_error($ch);
exit;
}
// parse the html into a DOMDocument
$dom = new DOMDocument();
#$dom->loadHTML($html);
// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body/div[#id='pagewrap']/div[#id='content']/div[#id='bottomSection']/div[#id='bottomRight']/div[#id='sideDeal']/div[2]/div/a/center/span");
foreach ($hrefs as $e) {
$e->nodeValue;
}
$insert = $e->nodeValue;
echo "$insert";
--EDIT--
No luck...
Fatal error: Call to a member function loadHTMLfile() on a non-object in ... Line 4
//
$xpath_query = $dom->loadHTMLfile("http://www.teambuy.ca/vancouver/");
$hrefs = $xpath_query->evaluate("/html/body/div[7]/div[4]/div[3]/div[2]/div[1]/div[2]/div/a/center/span");
foreach ($hrefs as $e) {
echo $e->nodeValue;
}
$insert = $e->nodeValue;
echo "$insert";
don't use cURL. just use
$dom->loadHTMLFile("http://www.teambuy.ca/calgary/");
don't use
$xpath = new DOMXPath($dom);
just use
$href = $dom->xpath($xpath_query);
I imagine your xpath query could be simplified as well...
also,
foreach ($hrefs as $e) {
$e->nodeValue;
}
does nothing. might want to try this instead.
foreach ($hrefs as $e) {
echo $e->nodeValue;
}

Categories