How to output the contents of file_get_contents - php

I'm trying to figure out how to get a php file (html, css and javascript) and load it into the content section below.
The following is the original...
function wpse_124979_add_help_tabs() {
if ($screen = get_current_screen()) {
$help_tabs = $screen->get_help_tabs();
$screen->remove_help_tabs();
$screen->add_help_tab(array(
'id' => 'my_help_tab',
'title' => 'Help',
'content' => 'HTML CONTENT',
I have tried the following but fails. I added a file_get_contents (first line), and then tried pull it in with 'content' => $adminhelp,
The following is with my amended code...
$adminhelp = file_get_contents('admin-help.php');
function wpse_124979_add_help_tabs() {
if ($screen = get_current_screen()) {
$help_tabs = $screen->get_help_tabs();
$screen->remove_help_tabs();
$screen->add_help_tab(array(
'id' => 'my_help_tab',
'title' => 'WTV Help',
'content' => $adminhelp,
Any ideas what's wrong?

If you want the output of the PHP file to be saved as $adminhelp use:
$adminhelp = file_get_contents('http://YOUR_DOMAIN/admin-help.php');
Right now you're loading the source code of admin-help.php into $adminhelp.
Another example for getting the output of a webpage is cURL:
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "http://YOUR_DOMAIN/admin-help.php");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$adminhelp = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
If this doesn't answer your question, please include the error message that you're receiving.

Related

Unable to get Healthline search results with PHP

I am trying to run a script that will search Healthline with a query string and determine if there are any search results, but I can't get the contents with the query string posting to the page. To search for something on their site, you go to https://www.healthline.com/search?q1=search+string.
Here is what I tried:
$healthline_url = 'https://www.healthline.com/search';
$search_string = 'ashwaganda';
$postdata = http_build_query(
array(
'q1' => $search_string
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$stream = stream_context_create($opts);
$theHtmlToParse = file_get_contents($healthline_url, false, $stream);
print_r($theHtmlToParse);
I also tried to just add the query string to the url and skip the stream, amongst other variations, but I'm running out of ideas. This also didn't work:
$healthline_url = 'https://www.healthline.com/search';
$search_string = 'ashwaganda';
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Content-Type: text/xml; charset=utf-8"
)
);
$stream = stream_context_create($opts);
$theHtmlToParse = file_get_contents($healthline_url.'&q1='.$search_string, false, $stream);
print_r($theHtmlToParse);
And suggestions?
EDIT: I changed the url in case someone wants to look at the search page. Also fixed the query string. Still doesn't work.
In response to Ken Lee, I did try the following cURL script that also just returns the page without search results:
$healthline_url = 'https://www.healthline.com/search?q1=ashwaganda';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $healthline_url);
$data = curl_exec($ch);
curl_close($ch);
print_r($data);
Healthline does not load the search result directly. It has its search index stored in Algolia and made extra javascript calls to retrieve the result. Therefore you cannot see the search result by file_get_content.
To see the search result, you need to run a browser simulator that simulates a javascript-capable browser to properly run the site page.
For PHP developers, you may try using php-webdriver to control browers through webdriver (e.g. Selenium, Chrome + chromedriver, Firefox + geckodriver).
Update: Didn't know that the target site is Healthline. Updated the answer once I found out.

PHP cURL & XPath giving inconsistent results

trying to do a loop with a url parameter, into a function which does a curl, gets all html and runs xpath on it. But the results varies. Is there something special I need to consider using curl or xpath? Sometimes it collects an emtpy string. The code works, just this flaw that is really hard to debug.
Here is the code I use.
private function getArticles($url){
// Instantiate cURL to grab the HTML page.
$c = curl_init($url);
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_USERAGENT, $this->getUserAgent());
curl_setopt($c, CURLOPT_FAILONERROR, true);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($c, CURLOPT_AUTOREFERER, true);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_TIMEOUT, 10);
// Grab the data.
$html = curl_exec($c);
// Check if the HTML didn't load right, if it didn't - report an error
if (!$html) {
echo "<p>cURL error number: " .curl_errno($c) . " on URL: " . $url ."</p>" .
"<p>cURL error: " . curl_error($c) . "</p>";
}
// Close connection.
curl_close($c);
// Parse the HTML information and return the results.
$dom = new DOMDocument();
#$dom->loadHtml($html);
$xpath = new DOMXPath($dom);
// Get a list of articles from the section page
$cname = $xpath->query('//*[#id="item-details"]/div/div[1]/h1');
$link = $xpath->query('//*[#id="item-details"]/div/ul/li[1]/a/#href');
$streetadress = $xpath->query('//*[#id="item-details"]/div[2]/div[3]/div[1]/text()[1]');
$zip = $xpath->query('//*[#id="item-details"]/div[2]/div[3]/div[1]/text()[2]');
$phone1 = $xpath->query('//*[#id="item-details"]/div/h2/span[2]');
$phone2 = $xpath->query('//*[#id="item-details"]/div/h2[2]/span[2]');
$ceo = $xpath->query('//*[#id="company-financials"]/div/div[2]/span');
$orgnr = $xpath->query('//*[#id="company-financials"]/div/div[1]/span');
$turnover13 = $xpath->query('//*[#class="geb-turnover1"]');
$turnover12 = $xpath->query('//*[#class="geb-turnover2"]');
$turnover11 = $xpath->query('//*[#class="geb-turnover3"]');
$logo = $xpath->query('//*[#id="item-info"]/p/img/#src');
$desc = $xpath->query('//*[#id="item-info"]/div[1]/div');
$capturelink = "";
// $capturelink = $this->getWebCapture($link->item(0)->nodeValue);
return array(
'companyname' => $cname->item(0)->nodeValue,
'streetadress' => $streetadress->item(0)->nodeValue,
'zip' => $zip->item(0)->nodeValue,
'phone1' => $phone1->item(0)->nodeValue,
'phone2' => $phone2->item(0)->nodeValue,
'link' => $link->item(0)->nodeValue,
'ceo' => $ceo->item(0)->nodeValue,
'orgnr' => $orgnr->item(0)->nodeValue,
'turnover2013' => $turnover13->item(0)->nodeValue,
'turnover2012' => $turnover12->item(0)->nodeValue,
'turnover2011' => $turnover11->item(0)->nodeValue,
'description' => $desc->item(0)->nodeValue,
'logo' => $logo->item(0)->nodeValue,
'capturelink' => $capturelink);
}
// End Get Articles
Edit:
I really tried everything on this one. But ended up using phpQuery and now it works. I do think php dom and xpath combined is not always a good mix. At least for me in this case.
This how I use it instead of xpath:
....
require('phpQuery.php');
phpQuery::newDocumentHTML($html);
$capture = "";
// $capture = $this->getWebCapture(pq('.website')->attr('href'));
return array(
'companyname' => pq('.header')->find('h1')->text(),
'streetadress' => pq('.address-container:first-child')->text(),
'zip' => pq('.address-container')->text(),
'phone1' => pq('.phone-number')->text(),
'phone2' => pq('.phone-number')->text(),
'link' => pq('.website')->attr('href'),
'ceo' => pq('.geb-ceo')->text(),
'orgnr' => pq('.geb-org-number')->text(),
'turnover2013' => pq('.geb-turnover1')->text(),
'turnover2012' => pq('.geb-turnover2')->text(),
'turnover2011' => pq('.geb-turnover3')->text(),
'description' => pq('#item-info div div')->text(),
'logo' => pq('#item-info logo img')->attr('src'),
'capture' => $capture);
Is there something special I need to consider using curl or xpath?
As you ask that actually, I think you could benefit from making yourself more comfortable what the curl thingy is about and what the xpath thingy is about and at which point both are related and where not.
The code works, just this flaw that is really hard to debug.
Well, the function you've got there is pretty long and does too many things at once. That is why it's hard to debug, too. Move code out of that function into subroutines you call from that function. That will also help you to structure the code more.
Additionally you can keep records of the activity your program does. So you can in debugging for example take the exact same HTML of a past request (because you've stored it) and verify if your xpath queries are really fitting for the data.

PHP Curl - Wistia API Upload

I'm trying to upload a movie to the Wistia API by CURL (http://wistia.com/doc/upload-api).
It works fine using the following command line, but when I put it in PHP code, I just get a blank screen with no response:
$ curl -i -d "api_password=<YOUR_API_PASSWORD>&url=<REMOTE_FILE_PATH>" https://upload.wistia.com/
PHP Code:
<?php
$data = array(
'api_password' => '<password>',
'url' => 'http://www.mysayara.com/IMG_2183.MOV'
);
$chss = curl_init('https://upload.wistia.com');
curl_setopt_array($chss, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => json_encode($data)
));
// Send the request
$KReresponse = curl_exec($chss);
// Decode the response
$KReresponseData = json_decode($KReresponse, TRUE);
echo("Response:");
print_r($KReresponseData);
?>
Thanks.
For PHP v5.5.0 or later, here's a class for uploading to Wistia, from a LOCALLY STORED file.
Usage:
$result = WistiaUploadApi::uploadVideo("/var/www/mysite.com/tmp_videos/video.mp4","video.mp4","abcdefg123","Test Video", "This is a video upload demonstration");
The class:
#param $file_path Full local path to the file
#param $file_name The name of the file (not sure what Wistia does with this)
#param $project The 10 character project identifier the video will upload to
#param $name The name the video will have on Wistia
#param $description The description the video will have on Wistia
class WistiaUploadApi
{
const API_KEY = "<API_KEY_HERE>";
const WISTIA_UPLOAD_URL = "https://upload.wistia.com";
public static function uploadVideo($file_path, $file_name, $project, $name, $description='')
{
$url = self::WISTIA_UPLOAD_URL;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
$params = array
(
'project_id' => $project,
'name' => $name,
'description' => $description,
'api_password' => self:: API_KEY,
'file' => new CurlFile($file_path, 'video/mp4', $file_name)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//JSON result
$result = curl_exec($ch);
//Object result
return json_decode($result);
}
}
If you don't have a project to upload into, leaving $project blank will NOT apparently force Wistia to create one. It will just fail. So you might have to remove this from the $params array if you don't have a project to upload to. I've not experimented to see what happens when you leave $name blank.
Your problem (and the difference between the command line and PHP implementation) is probably that you're JSON encoding the data in PHP, you should use http_build_query() instead:
CURLOPT_POSTFIELDS => http_build_query($data)
For clarity, the Wistia API says it returns JSON, but doesn't expect it in the request.

Pastebin API Paste Data

I've been trying to get the pastebin API to instead of telling me the pastebin link , just output the raw data. The PHP code is this :
<?php
$api_dev_key = 'Stackoverflow(fake key)';
$api_paste_code = 'API.'; // your paste text
$api_paste_private = '1'; // 0=public 1=unlisted 2=private
$api_paste_expire_date = 'N';
$api_paste_format = 'php';
$api_paste_code = urlencode($api_paste_code);
$url = 'http://pastebin.com/api/api_post.php';
$ch = curl_init($url);
?>
Normally this would upload the $api_paste_code into pastebin , showing up like pastebin.com/St4ck0v3RFL0W , but instead I want it to generate the raw data.
The raw data link is http://pastebin.com/raw.php?i= , can anyone help?
Reference : http://pastebin.com/api
As far as I see, the response contains the Pastebin URL generated when the content is created. An Url like this:
http://pastebin.com/UIFdu235s
So what you only need is to get rid of "http://pastebin.com/" doing:
$id = str_replace("http://pastebin.com/", "", $url_received_on_last_step);
And then, append it to the raw url you provided:
$url_raw = "http://pastebin.com/raw.php?i=".$id;
And you'll get the raw data.
First off, please note that you must send a POST request to the pastebin.com API, not GET. So don't use urlencode() on your input data!
To get the raw paste url from the page url, you have several options. But the easiest is probably:
$apiResonse = 'http://pastebin.com/ABC123';
$raw = str_replace('m/', 'm/raw.php?i=', $apiResponse);
Finally, here is a complete example:
<?php
$data = 'Hello World!';
$apiKey = 'xxxxxxx'; // get it from pastebin.com
$apiHost = 'http://pastebin.com/';
$postData = array(
'api_dev_key' => $apiKey, // your dev key
'api_option' => 'paste', // action to perform
'api_paste_code' => utf8_decode($data), // the paste text
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => "{$apiHost}api/api_post.php",
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => http_build_query($postData),
));
$result = curl_exec($ch); // on success, some string like 'http://pastebin.com/ABC123'
curl_close($ch);
if ($result) {
$pasteId = str_replace($apiHost, '', $result);
$rawLink = "{$apiHost}raw.php?i={$pasteId}";
echo "Created new paste.\r\n Paste ID:\t{$pasteId}\r\n Page Link:\t{$result}\r\n Raw Link:\t{$rawLink}\r\n";
}
Running the above code, outputs:
c:\xampp\htdocs>php pastebin.php
Created new paste.
Paste ID: Bb8Ehaa7
Page Link: http://pastebin.com/Bb8Ehaa7
Raw Link: http://pastebin.com/raw.php?i=Bb8Ehaa7

Send parameters to a URL and get output from that page

I have 2 pages say abc.php and def.php. When abc.php sends 2 values [id and name] to def.php, it shows a message "Value received". Now how can I send those 2 values to def.php without using form in abc.php and get the "Value received" message from def.php? I can't use form because when user frequently visits the abc.php file, the script should automatically work and get the message "Value received" from def.php. Please see my example code:
abc.php:
<?php
$id="123";
$name="blahblah";
//need to send the value to def.php & get value from that page
// echo $value=Print the "Value received" msg from def.php;
?>
def.php:
<?php
$id=$_GET['id'];
$name=$_GET['name'];
if(!is_null($id)&&!is_null($name))
{ echo "Value received";}
else{echo "Not ok";}
?>
Is there any kind heart who can help me solve the issue?
First make up your mind : do you want GET or POST parameters.
Your script currently expects them to be GET parameters, so you can simply call it (provided that URL wrappers are enabled anyway) using :
$f = file_get_contents('http://your.domain/def.php?id=123&name=blahblah');
To use the curl examples posted here in other answers you'll have to alter your script to use $_POST instead of $_GET.
You can try without cURL (I havent tried though):
Copy pasted from : POSTing data without cURL extension
// Your POST data
$data = http_build_query(array(
'param1' => 'data1',
'param2' => 'data2'
));
// Create HTTP stream context
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $data
)
));
// Make POST request
$response = file_get_contents('http://example.com', false, $context);
Taken from the examples page of php.net:
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com/abc.php");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
Edit: To send parameters
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( tch, CURLOPT_POSTFIELDS, array('var1=foo', 'var2=bar'));
use CURL or Zend_Http_Client.
<?php
$method = 'GET'; //change to 'POST' for post method
$url = 'http://localhost/browse/';
$data = array(
'manufacturer' => 'kraft',
'packaging_type' => 'bag'
);
if ($method == 'POST'){
//Make POST request
$data = http_build_query($data);
$context = stream_context_create(array(
'http' => array(
'method' => "$method",
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $data)
)
);
$response = file_get_contents($url, false, $context);
}
else {
// Make GET request
$data = http_build_query($data, '', '&');
$response = file_get_contents($url."?".$data, false);
}
echo $response;
?>
get inspired by trix's answer, I decided to extend that code to cater for both GET and POST method.

Categories