So I am working on a website based off of something called the Hypixel API.
When I use a forum where a user can input a name, I get a response of
Player == nullArray ( [0] => Array ( [success] => [cause] => [status] => 204 ) [1] => Array ( [success] => [cause] => [status] => 204 ) )
This is my code:
<?php
$ign = $_GET['ign'];
include_once('HypixelPHP.php');
$HypixelPHP = new HypixelPHP\HypixelPHP(['api_key' => 'BLOCKED']);
// get a player object using the hypixel api object
$player = $HypixelPHP->getPlayer([\HypixelPHP\KEYS::PLAYER_BY_NAME => '$ign']);
if ($player != null) {
echo 'View stats for ' . $player->getFormattedName(true, true);
echo '<br>';
echo '<h1>GAME STATS</h1>';
echo '<h3>Mega Walls</h3>';
echo 'Wins: ' . $player->getStats()->getGameFromID(\HypixelPHP\GameTypes::WALLS3)->getInt('wins');
echo '<br>';
echo 'Kills: ' . $player->getStats()->getGameFromID(\HypixelPHP\GameTypes::WALLS3)->getInt('kills');
echo '<br>';
echo 'Final Kills: ' . $player->getStats()->getGameFromID(\HypixelPHP\GameTypes::WALLS3)->getInt('final');
echo '<br>';
} else {
echo 'Player == null';
print_r($HypixelPHP->getUrlErrors());
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
</head>
</html>
In the form, I did do the name thing correct.
This should be the output:
Along with some other stuff.
If you guys can help, thank you!
The issue is that you are passing the single quoted string '$ign'. This ignored the variable you have set for $ign.
http://php.net/manual/en/language.types.string.php
Related
I need to read three lines of a remote page using PHP. I'm using code from Jose Vega found here to read the title:
<?php
function get_title($url){
$str = file_get_contents($url);
if(strlen($str)>0){
$str = trim(preg_replace('/\s+/', ' ', $str)); // supports line breaks inside <title>
preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title); // ignore case
return $title[1];
}
}
//Example:
echo get_title("http://www.washingtontimes.com/");
?>
When I plug in a URL, I want to extract the following information:
<title>TITLE HERE</title>
<meta property="end_date" content="Tue Aug 28 2018 03:59:59 GMT+0000 (UTC)" />
<meta property="start_date" content="Mon Aug 06 2018 04:00:00 GMT+0000 (UTC)" />
Outputs: $title, $start, $end
Displayed as a title with a link to URL, followed by Starts: ____, Ends: ____, preferably converted to simple dates
Bonus Question: How can I efficiently parse dozens of sites using this script? The sites are all ascending numerically. index.php?id=103 index.php?id=104 index.php?id=105
Displaying:
ID Title Start End
#103 TitleWithLink StartDate EndDate
#104 TitleWithLink StartDate EndDate
#105 TitleWithLink StartDate EndDate
Based on your question i guessed you want to read metadata.A part of the code i will suggest now has been taken from http://php.net/manual/en/function.get-meta-tags.php
.It works fine for this SO page so it will work fine for yours too.Of course you will need to adapt it a little to get your task done.
function getUrlData($url, $raw=false) // $raw - enable for raw display
{
$result = false;
$contents = getUrlContents($url);
if (isset($contents) && is_string($contents))
{
$title = null;
$metaTags = null;
$metaProperties = null;
preg_match('/<title>([^>]*)<\/title>/si', $contents, $match );
if (isset($match) && is_array($match) && count($match) > 0)
{
$title = strip_tags($match[1]);
}
preg_match_all('/<[\s]*meta[\s]*(name|property)="?' . '([^>"]*)"?[\s]*' . 'content="?([^>"]*)"?[\s]*[\/]?[\s]*>/si', $contents, $match);
if (isset($match) && is_array($match) && count($match) == 4)
{
$originals = $match[0];
$names = $match[2];
$values = $match[3];
if (count($originals) == count($names) && count($names) == count($values))
{
$metaTags = array();
$metaProperties = $metaTags;
if ($raw) {
if (version_compare(PHP_VERSION, '5.4.0') == -1)
$flags = ENT_COMPAT;
else
$flags = ENT_COMPAT | ENT_HTML401;
}
for ($i=0, $limiti=count($names); $i < $limiti; $i++)
{
if ($match[1][$i] == 'name')
$meta_type = 'metaTags';
else
$meta_type = 'metaProperties';
if ($raw)
${$meta_type}[$names[$i]] = array (
'html' => htmlentities($originals[$i], $flags, 'UTF-8'),
'value' => $values[$i]
);
else
${$meta_type}[$names[$i]] = array (
'html' => $originals[$i],
'value' => $values[$i]
);
}
}
}
$result = array (
'title' => $title,
'metaTags' => $metaTags,
'metaProperties' => $metaProperties,
);
}
return $result;
}
function getUrlContents($url, $maximumRedirections = null, $currentRedirection = 0)
{
$result = false;
$contents = #file_get_contents($url);
// Check if we need to go somewhere else
if (isset($contents) && is_string($contents))
{
preg_match_all('/<[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^>"]*)"?' . '[\s]*[\/]?[\s]*>/si', $contents, $match);
if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1)
{
if (!isset($maximumRedirections) || $currentRedirection < $maximumRedirections)
{
return getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
}
$result = false;
}
else
{
$result = $contents;
}
}
return $contents;
}
$result = getUrlData('https://stackoverflow.com/questions/51939042/php-read-three-lines-of-remote-html', true);
the output of print_r($result); is:
Array
(
[title] => file get contents - PHP - Read three lines of remote html - Stack Overflow
[metaTags] => Array
(
[viewport] => Array
(
[html] => <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0">
[value] => width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0
)
[twitter:card] => Array
(
[html] => <meta name="twitter:card" content="summary"/>
[value] => summary
)
[twitter:domain] => Array
(
[html] => <meta name="twitter:domain" content="stackoverflow.com"/>
[value] => stackoverflow.com
)
[twitter:app:country] => Array
(
[html] => <meta name="twitter:app:country" content="US" />
[value] => US
)
[twitter:app:name:iphone] => Array
(
[html] => <meta name="twitter:app:name:iphone" content="Stack Exchange iOS" />
[value] => Stack Exchange iOS
)
[twitter:app:id:iphone] => Array
(
[html] => <meta name="twitter:app:id:iphone" content="871299723" />
[value] => 871299723
)
[twitter:app:url:iphone] => Array
(
[html] => <meta name="twitter:app:url:iphone" content="se-zaphod://stackoverflow.com/questions/51939042/php-read-three-lines-of-remote-html" />
[value] => se-zaphod://stackoverflow.com/questions/51939042/php-read-three-lines-of-remote-html
)
[twitter:app:name:ipad] => Array
(
[html] => <meta name="twitter:app:name:ipad" content="Stack Exchange iOS" />
[value] => Stack Exchange iOS
)
[twitter:app:id:ipad] => Array
(
[html] => <meta name="twitter:app:id:ipad" content="871299723" />
[value] => 871299723
)
[twitter:app:url:ipad] => Array
(
[html] => <meta name="twitter:app:url:ipad" content="se-zaphod://stackoverflow.com/questions/51939042/php-read-three-lines-of-remote-html" />
[value] => se-zaphod://stackoverflow.com/questions/51939042/php-read-three-lines-of-remote-html
)
[twitter:app:name:googleplay] => Array
(
[html] => <meta name="twitter:app:name:googleplay" content="Stack Exchange Android">
[value] => Stack Exchange Android
)
[twitter:app:url:googleplay] => Array
(
[html] => <meta name="twitter:app:url:googleplay" content="http://stackoverflow.com/questions/51939042/php-read-three-lines-of-remote-html">
[value] => http://stackoverflow.com/questions/51939042/php-read-three-lines-of-remote-html
)
[twitter:app:id:googleplay] => Array
(
[html] => <meta name="twitter:app:id:googleplay" content="com.stackexchange.marvin">
[value] => com.stackexchange.marvin
)
)
[metaProperties] => Array
(
[og:url] => Array
(
[html] => <meta property="og:url" content="https://stackoverflow.com/questions/51939042/php-read-three-lines-of-remote-html"/>
[value] => https://stackoverflow.com/questions/51939042/php-read-three-lines-of-remote-html
)
[og:site_name] => Array
(
[html] => <meta property="og:site_name" content="Stack Overflow" />
[value] => Stack Overflow
)
)
)
Then to actually use it to achieve your purpose:
How can I efficiently parse dozens of sites using this script? The
sites are all ascending numerically. index.php?id=103 index.php?id=104
index.php?id=105
you need to :
-first create an array containing your urls
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>HTML Table</h2>
<table>
<tr>
<th >Id</th>
<th >Title</th>
<th >start_date</th>
<th>end_date</th>
</tr>
<?php
$urls=array(103=>'index.php?id=103',104=> 'index.php?id=104', 105=>'index.php?id=105');
-then loop through this array :
foreach($urls as $id=>$url):
-each iteration you use the function getUrlData() as shown:
$result=getUrlData($url, true);
-then you retrieve the needed information using eg:
?><tr>
<td><?php echo $id; ?></td>
<td><?php echo $result['title']; ?></td>
<td><?php echo $result['metaProperties']['start_date']['value']; ?></td>
<td><?php echo $result['metaProperties']['end_date']['value']; ?></td>
</tr>
to build each line and row.
At the end of the process you would have get your expected table:
Endforeach;?>
</table></body>
</html>
Well, you could solve your issue with the DomDocument class.
$doc = new \DomDocument();
$title = $start = $end = '';
if ($doc->loadHTMLFile($url)) {
// Get the title
$titles = $dom->getElementsByTagName('title');
if ($titles->length > 0) {
$title = $titles->item(0)->nodeValue;
}
// get meta elements
$xpath = new \DOMXPath($doc);
$ends = $xpath->query('//meta[#property="end_date"]');
$if ($ends->length > 0) {
$end = $ends->item(0)->getAttribute('content');
}
$starts = $xpath->query('//meta[#property="start_date"]');
if ($starts->length > 0) {
$start = $starts->item(0)->getAttribute('content');
}
var_dump($title, $start, $end);
}
With the getElementsByTagName method of the DomDocument class you can find the title element in the whole html of a given url. With the DOMXPath class you can retrieve the specific meta data you want. You don 't need much code for finding specific informations in a html string.
The code shown above is not tested.
despite my efforts I wasn't able to find a suitable solution. Here is the problem:
All the data comes from a form with text fields named name[], gender[], and age[].
print_r($_POST) looks like:
[name] => Array ([2] => Adam [6] => Suzy )
[gender] => Array ( [2] => male [6] => female )
[age] => Array ( [2] => 30 [6] => 25 )
I am trying to iterate it like this:
foreach ($array as $value)
{
echo $value['name'].$value['gender'].$value['age']."<br>";
}
The result should look like this:
Adam - male - 30
Suzy - female - 25
You are close - but the syntax for creating arrays is slightly different.
$array = array (
array('name' => 'Adam', 'gender' => 'male', 'age' => 30),
array('name' => 'Suzy', 'gender' => 'female', 'age' => 25),
);
foreach ($array as $value)
{
echo $value['name'].$value['gender'].$value['age']."<br>";
}
You've got two options - you could create an array of two items; each has three details about a single person. That's what I did and it suits the loop you've shown.
Or you can have three parallel arrays - one with two names, one with two genders and one with two ages.
That second way would look more like:
$array = array(
'name' => array('Adam','Suzy'),
'gender' => array('male','female'),
'age' => array(30,25)
);
But it would be harder to get the output you want from that.
$array2 = array(
'name' => array('Adam','Suzy'),
'gender' => array('male','female'),
'age' => array(30,25)
);
for($i=0;$i<count($array2['name']);$i++){
echo $array2['name'][$i].$array2['gender'][$i].$array2['age'][$i].'<br/>';
}
Each of the arrays in $_POST have the same set of keys:
$_POST = array(
'name' => array(2 => 'Adam', 6 => 'Suzy'),
'gender' => array(2 => 'male', 6 => 'female'),
'age' => array(2 => '30', 6 => '25')
)
You can iterate one of the inner arrays, and use its key to access the corresponding values in the other arrays.
foreach ($_POST['name'] as $key => $name) {
echo $name . $_POST['gender'][$key] . $_POST['age'][$key] . "<br>";
}
foreach ($array as $id=>$value)
{
echo $value . $gender[$id] . $age[$id] . "<br>";
}
First of all I've modified the array structure that you posted on your question because it is not valid for in php. Then If I don't misunderstood you requirements then you've this array structure and you want to archive this-
<?php
$array = array (
'name'=>array('Adam', 'Suzy'),
'gender'=>array('male', 'female'),
'age'=>array(30, 25)
);
$i=0;
foreach ($array as $key=>$value)
{
if($i==2)break;
echo $array['name'][$i]."-".$array['gender'][$i] ."-". $array['age'][$i] ."<br>";
$i++;
}
?>
OR
<?php
$array = array (
'name'=>array('Adam', 'Suzy'),
'gender'=>array('male', 'female'),
'age'=>array(30, 25)
);
foreach ($array['name'] as $index=>$name)
{
echo $name."-".$array['gender'][$index] ."-". $array['age'][$index] ."\n";
}
?>
Program Output:
Adam-male-30
Suzy-female-25
DEMO: https://eval.in/1039966
#Being Sunny
Veeeery close to that sir I'v used back in 2003. Here is the working solution:
<?
echo "<pre>";
print_r($_POST);
echo "</pre>";
foreach ($_POST['name'] as $key => $name) {
echo "NAME=".$_POST['name'][$key]."gender=" . $_POST['gender'][$key] . "AGE=".$_POST['age'][$key] . "<br>";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
</head>
<body>
WOKSING SOLUTION:
<code>echo "<pre>";
print_r($_POST);
echo "</pre>";
foreach ($_POST['name'] as $key => $name) {
echo "NAME=".$_POST['nemae'][$key]."gender=" . $_POST['gender'][$key] . "AGE=".$_POST['age'][$key] . "<br>";
}
</code>
<form method="post">
<input type="text" name="name[]" />
<input type="text" name="gender[]"/>
<input type="text" name="age[]"/>
<br />
<input type="text" name="name[]" />
<input type="text" name="gender[]"/>
<input type="text" name="age[]"/>
<input type="submit" />
</form>
</body>
</html>
Whenever I run this code through the SalesForce PHP api, it fails with err:Notice: Trying to get property of non-object
$query ="SELECT accountId,Status,Id,Service_Account_DMKT__r.name,(select Activity_Type__c from Tasks) from case where Owner.Name ='" . $name . "' AND CreatedDate = THIS_MONTH AND Record_type_name__c='Performance Reviews' AND status NOT IN ('')";
$response = $mySforceConnection->query($query);
$queryResult = new QueryResult($response);
foreach($queryResult->records as $case){
//for ($queryResult->rewind(); $queryResult->pointer < $queryResult->size; $queryResult->next()) {
$callCounter = 0;
$emailCounter = 0;
$accountId = $case->current()->accountId;
$accountName=$case->current()->Service_Account_DMKT__r->Name;
$caseId= $case->current()->Id;
if($case->any['Tasks']->records) {
$counter=0;
foreach($case->any['Tasks']->records as $record) {
$taskRecord = $record->any;
if (strpos($taskRecord, 'Call - Outbound') !== false) {
$callCounter++;
} else {
$emailCounter++;
}
$counter++;
}
}
echo '<p>AccountName=' . $accountName . '</p><p>CaseId=' . $caseId . '</p>';
echo '<p>' . $callCounter . ' Calls and ' . $emailCounter . ' emails';
echo'<hr>';
$index++;
}
print_r($case);
I know it is because of these three lines. I'm not stepping through the object correctly.
$accountId = $case->current()->accountId;
$accountName=$case->current()->Service_Account_DMKT__r->Name;
$caseId= $case->current()->Id;
But I'm not sure what to use instead of current(). Below is the response object from the SF API
stdClass Object
(
[type] => Case
[Id] => Array
(
[0] => 5000e00001J7L0pAAF
[1] => 5000e00001J7L0pAAF
)
[any] => Array
(
[0] => 00130000002bqXiAAIClosed - Contact Declined5000e00001J7L0pAAF
[Service_Account_DMKT__r] => stdClass Object
(
[type] => Account
[Id] =>
[any] => brinsoncorsicanafordfd
)
[Tasks] => stdClass Object
(
[done] => 1
[queryLocator] =>
[records] => Array
(
[0] => stdClass Object
(
[type] => Task
[Id] =>
[any] =>
)
)
[size] => 1
)
)
)
I finally managed to fix it by converting the response back to another object
$query ="SELECT accountid,Status,Id,Service_Account_DMKT__r.name,(select Activity_Type__c,subject from Tasks) from case where Owner.Name ='" . $SFName . "' AND CreatedDate = THIS_MONTH AND Record_type_name__c='Performance Reviews' AND status NOT IN ('')";
$response = $mySforceConnection->query($query);
$queryResult = new QueryResult($response);
foreach($queryResult->records as $case){ //For every record within $queryResult
$callCounter = 0; //Set up our task counters
$emailCounter = 0;
$sObject = new SObject($case); //turn $case back into a SObj to easy step thru
$accountId= $sObject->AccountId; //Pull AccountId from $sObject
$accountName=$sObject->Service_Account_DMKT__r->Name;
$caseId=$sObject->Id;
$caseStatus=$sObject->Status;
if(!isset($sObject->queryResult)) { //Check if there are any tasks on the record, otherwise we'll get an error
$callCounter=0; //if there are no tasks, set counters to 0
$emailCounter=0;
}else{
$counter=0;
foreach($case->any['Tasks']->records as $record) { //for each task in the $case
$taskObject = new SObject($record); //Turn $record into taskObject so we can step through it.
$taskType = $taskObject->Activity_Type__c; //Pull the activity type out of TaskObject
if($taskType == "Call - Outbound"){ //Calling $taskType actually allows us to compare the obj to a string, where as going through this in an array format would not!
$callCounter++; //increase counter if the taskType is a call
} else {
$emailCounter++;
}
}
}
echo '<p>AccountName=' . $accountName . '</p><p>AccountID=' . $accountId . '</p><p>CaseId=' . $caseId . '</p><p>CaseStatus=' . $caseStatus . '</p>';
echo '<p>' . $callCounter . ' Calls and ' . $emailCounter . ' emails';
echo'<hr>';
}
I'm trying to get the comment information from a JPG. My example below returns ?
Because it's grabbing the wrong comment.
[WINXP] => Array ( [Comments] => ????????????????????????????????? )
While I need it to grab specifically,
[IFD0] => Array ( [Exif_IFD_Pointer] => 2110 [Comments]
Code:
<?php
$exif_data = exif_read_data('28058990_1835355009821464_5937004451156759325_n.jpg', 0, true);
echo $exif_data===false ? "No header data found.<br />\n" : "Image contains headers<br />\n";
echo $exif_data['Comments'];
print_r($exif_data);
?>
I ended up doing it this way..
<?php
$exif_data=exif_read_data('28058990_1835355009821464_5937004451156759325_n.jpg', 0, true);
$values=array();
foreach($exif_data as $exif => $key)
{
foreach($key as $value)
{
$items[] = $value;
}
}
echo '<img src='.$items[0].' width="256px"><br />'.$items[12];
?>
I'm using an API my teacher made. And So far I'm able to get some information out of it.
But I need to get certain information into variables, so I can push it to my database. I decodes the information so far, en it looks like this:
Array
(
[0] => stdClass Object
(
[homeClub] => Roda JC
[awayClub] => Feyenoord
)
[1] => stdClass Object
(
[homeClub] => SC Cambuur
[awayClub] => Feyenoord
)
[2] => stdClass Object
(
[homeClub] => Heracles Almelo
[awayClub] => Feyenoord
)
And so on
But now I need to get both homeClub and awayClub each in a seperate variable. And im stuck.
If anyone could help me, it would be great. This is my code so far:
$methods = array(
'wedstrijden?club=Feyenoord'
);
$method = $methods[0];
$data = json_decode(file_get_contents($url . $method));
print_rr($data);
function print_rr($data){
echo '<pre>';
print_r($data);
echo '</pre>';
}
<?php
foreach($data as $row) {
echo "home club is: " . $row->homeClub;
echo "away club is: " . $row->awayClub;
}
you could also decode the json as associative array:
change $data = json_decode(file_get_contents($url . $method));
to $data = json_decode(file_get_contents($url . $method), true);
and iterate using:
<?php
foreach($data as $row) {
echo "home club is: " . $row['homeClub'];
echo "away club is: " . $row['awayClub'];
}
Oh, and don't let SO'ers do your homework :P