Loop through two DOMNodeLists at once using DOMDocument class - php

I got an error saying
Object of class DOMNodeList could not be converted to string on line
This is the line which contains the error:
$output .= '<li><a target="_blank" href="' . $postURL . '">' .
$title->nodeValue . '</a></li>';
DOM
My code:
$postTitle = $xpath->query("//tr/td[#class='row1'][3]//span[1]/text()");
$postURL = $xpath->query("//tr/td[#class='row1'][3]//a/#href");
$output = '<ul>';
foreach ($postTitle as $title) {
$output .= '<li><a target="_blank" href="' . $postURL . '">' . $title->nodeValue . '</a></li>';
}
$output .= '</ul>';
echo $output;
How can I resolve the error?

You're fetching two independent node list from the DOM, iterate the first and try to use the second one inside the loop as a string. A DOMNodeList can not be cast to string (in PHP) so you get an error. Node lists can be cast to string in Xpath however.
You need to iterate the location path that is the same for booth list (//tr/td[#class='row1'][3]) and get the $title and $url inside the loop for each of the td elements.
$posts = $xpath->evaluate("//tr/td[#class='row1'][3]");
$output = '<ul>';
foreach ($posts as $post) {
$title = $xpath->evaluate("string(.//span[1])", $post);
$url = $xpath->evaluate("string(.//a/#href)", $post);
$output .= sprintf(
'<li><a target="_blank" href="%s">%s</a></li>',
htmlspecialchars($url),
htmlspecialchars($title)
);
}
$output .= '</ul>';
echo $output;

Related

Breaking with a divider if more than one inside foreach

$linkPairs returns the following:
array (size=2)
0 => string 'Test|https://www.test2.com' (length=26)
1 => string 'Test2|http://www.test2.com/' (length=27)
How would I be successful on breaking the links using a divider as this: Test | Test2 .. the format that I'm getting now is TestTest2.
So I have the following code:
$linkPairs = explode(",", $atts['link']); // separate the pairs
$output = '';
$output .= '<li class="slide">
<p><img src="' . esc_url($atts['image']) . '" alt="" /></p>
<p>'. $atts['headline'] .'</p>
<p>'. $atts['body'] .'</p>';
foreach($linkPairs as $linkPair) {
$pair = explode("|", $linkPair); // separate the title and url
$output .= '' . $pair[0] . '';
}
$output .= '</li>';
One method to do it, would be add the links to an array, and implode them with what you wish to have separate them:
$output .= '<li class="slide">
<p><img src="' . esc_url($atts['image']) . '" alt="" /></p>
<p>'. $atts['headline'] .'</p>
<p>'. $atts['body'] .'</p>';
$hrefs = array();// define and clean for this item
foreach($linkPairs as $linkPair) {
$pair = explode("|", $linkPair); // separate the title and url
$hrefs[] = '' . $pair[0] . '';
}
$output .= implode(' | ',$hrefs);// implode them here
$output .= '</li>';
The imploded pipe, is not to be confused with the original pipe used in the raw data you work with. You mentioned you wanted to space your hrefs with a pipe, so that is the example above.
Update your foreach to add the divider, then rtrim() the last one
$divider = ' | ';
foreach($linkPairs as $linkPair) {
$pair = explode("|", $linkPair); // separate the title and url
$output .= '' . $pair[0] . ''.$divider;
}
$output = rtrim($output,$divider);
since it's good to know all possible ways you can also do the following count number of elements inthe linkPairs array then track the array pointer location to know the last link so that you don't add | to the last entry. I have explained everything i added in comment infront of the line.
$linkPairs = explode(",", $atts); // separate the pairs
$output = '';
$output .= '<li class="slide">
<p><img src="' . esc_url($atts['image']) . '" alt="" /></p>
<p>'. $atts['headline'] .'</p>
<p>'. $atts['body'] .'</p>';
$li=count($linkPairs);//number of element of array
$i=1;//track the current location of array_pointer
foreach($linkPairs as $linkPair) {
if($i!=$li){
$symbol="|";//add | if the link is not the last link
}
else {
$symbol="";//add nothing if the link is the last link
}
$pair = explode("|", $linkPair); // separate the title and url
$output .= '' . $pair[0] . ''.$symbol;//$symbol is used to add | to the link
$i++;
}
$output .= '</li>';

recursive function inside for loop

I m trying to create html in the controller instead of js.
There is an array with unknown depth of arrays.
$tree = $repo->childrenHierarchy();
and a function who reads the array and returns a string of html with values from array elements.
public function recursive($tree) {
$html = "";
foreach ($tree as $t) {
$html = $html . '<li> <span><i class="fa fa-lg fa-minus-circle"></i>' . $t['title'] . '</span>';
if ($t['__children'] != null) {
$html = $html . '<ul>';
$this->recursive($t['__children']);
$html = $html . '</ul>';
} else {
$html = $html . '</li>';
}
return $html;
}
My problem is that i cant hold the total string because everytime the function calls itself the var html is initialised, need to hold the string something like global but cant figure how.
After looking at this a little more, I don't think it really looks like a problem that the $html is initialized in the recursive calls. It seems to me that it actually should start as empty for the children. But it doesn't look like you're appending the children to the $html string you already have going. I think you need
$this->recursive($t['__children']);
to be instead
$html .= $this->recursive($t['__children']);
there shouldnt be anything wrong with just storing that value in class property while action ?
public $html = "";
public function recursive($tree) {
foreach ($tree as $t) {
$this->html = $this->html . '<li> <span><i class="fa fa-lg fa-minus-circle"></i>' . $t['title'] . '</span>';
if ($t['__children'] != null) {
$this->html = $this->html . '<ul>';
$this->recursive($t['__children']);
$this->html = $this->html . '</ul>';
} else {
$this->html = $this->html . '</li>';
}
return $this->html;
}

Google Analytics event tracking with PHP in html_output

I'm getting category from my database using PHP and I want to use it inside Google Analytics event tracking code. The problem is that events are not being recorded in Google Analytics.
Here are some code snippets from my project:
1)
$docs = array();
while ($row = mysql_fetch_assoc($result)) {
$doc = array();
$doc['my_tel'] = $row['my_tel'];
$doc['my_category'] = $row['my_category'];
$docs[] = $doc;
}
mysql_free_result($result);
2)
<?php
$html_output = '';
foreach ($docs as &$d) {
$html_output .= '<div>' .
'<img src="call.png" width="65px" height="35px" border="0">' .
'</div>';
}
echo $html_output;
?>
If you have a look at the console of your browser there might be a JavaScript error, because the second parameter of _gaq.push is not wrapped with quotes.
Try this:
<?php
$html_output = '';
foreach ($docs as &$d) {
$html_output .= '<div>' .
'<img src="call.png" width="65px" height="35px" border="0">' .
'</div>';
}
echo $html_output;
?>
Looking at your append to $html_output, it appears you're not enclosing the category within single quotes in the resultant javascript output.
Assuming for example my_tel was 01234567890 and category was 'Category 1' the output from the code above would be:
<div><img src="call.png" width="65px" height="35px" border="0"></div>
Perhaps try (note additional escaped quotes around category:
'<a href="tel:' . $d['my_tel'] . '" onClick="_gaq.push([\'_trackEvent\', \'' . $d['my_category'] . '\', \'Event Action\',...
--dan

Print specific array value via function argument

$menu = array(
0 =>'top',
1 =>'photography',
2 =>'about'
);
<?php
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach( $menu as $key => $value)
{
$return .= '<a class="menu" href="index.php#' . $menu[$key] . '">' . $menu[$key] . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
?>
<?php echo main_menu($menu[1]); ?>
What i basically want to do is to pass a specific array value when i'm echoing out the menu.
I'm building a single page website with anchors and i want to pass value's so i can echo out the "top"-link.
I'm stuck at the point on how to pass the $key value trough the function.
**edit: I'm trying to print specific links. I want a function that is able to print out an link but i want to specify the link to print via the function argument.
for example:
<?php echo main_menu($key = '0'); ?>
result:
prints url: top
<?php echo main_menu($key = '2'); ?>
result:
prints url: photography
**
(A lack of jargon makes it a bit harder to explain and even harder to google.
I got my books in front of me but this is taking a lot more time than it should.)
You either need to pass the entire array and loop, or pass a single array item and not loop:
Single Item:
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
$return .= '<a class="menu" href="index.php#' . $menu . '">' . $menu . '</a>' . PHP_EOL .'';
$return .= '</div>';
return $return;
}
echo main_menu($menu[1]);
Entire Array:
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach($menu as $value) {
$return .= '<a class="menu" href="index.php#' . $value . '">' . $value . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
echo main_menu($menu);
You don't need $menu[$key] just use the $value.
Should you not just be using $value inside your loop? And passing the entire array rather than one item of the $menu array?
$menu = array(
0 =>'top',
1 =>'photography',
2 =>'about'
);
<?php
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach( $menu as $key => $value)
{
$return .= '<a class="menu" href="index.php#' . $value . '">' . $value . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
?>
<?php echo main_menu($menu); ?>
Try:
echo main_menu($menu); // You will get your links printed
Instead of
echo main_menu($menu[1]); // In this case error is occured like : **Invalid argument supplied for foreach**
NOTE: You can use $value instead of $menu[$key]

Need to create li with list of different links using php explode method

here is my working php explode code for NON links:
<?php
$textarea = get_custom_field('my_custom_output');
$array = explode(',',$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
$item = trim($item); // clear off white-space
$output .= '<li>' . $item . '</li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
..and the code which defines "my_custom_output", which I input into my textarea field:
text1,text2,text3,etc
..and the finished product:
text1
text2
text3
etc
So that works.
Now what I want to do is make text1 be a link to mywebsite.com/text1-page-url/
I was able to get this far:
<?php
$textarea = get_custom_field('my_custom_output');
$array = explode(',',$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
$item = trim($item); // clear off white-space
$output .= '<li class="link-class"><a title="' . $item . '" href="http://mywebsite.com/' . $item_links . '">' . $item . '</a></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
Now, I would like $item_links to define just the rest of the url. For example:
I want to put input this into my textarea:
text1:text1-page-url,text2:new-text2-page,text3:different-page-text3
and have the output be this:
text1
text2
..etc (stackoverflow forced me to only have two links in this post because I only have 0 reputation)
another thing I want to do is change commas to new lines. I know the code for a new line is \n but I do not know how to swap it out. That way I can put this:
text1:text1-page-url
text2:new-text2-page
text3:different-page-text3
I hope I made this easy for you to understand. I am almost there, I am just stuck. Please help. Thank you!
Just split the $item inside your loop with explode():
<?php
$separator1 = "\n";
$separator2 = ":";
$textarea = get_custom_field('my_custom_output');
$array = explode($separator1,$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
list($item_text, $item_links) = explode($separator2, trim($item));
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
And choose your string separators so $item_text, $item_links wouldn't contain them.
After you explode the string you could loop through again and separate the text and link into key/values. Something like...
$array_final = new array();
$array_temp = explode(',', $textarea);
foreach($array_temp as $item) {
list($text, $link) = explode(':', $item);
$array_final[$text] = $link;
}
foreach($array_final as $key => $value) {
echo '<li>'.$key.'</li>';
}
to change comma into new line you can use str_replace like
str_replace(",", "\r\n", $output)

Categories