Get id value with PHP Simple HTML DOM - php

I have this scenario:
<div class="listing_title">
<strong>
<a href="http://www.mywebsite.com/dectails23291.html" id="url_id_1977">
Listing Title
</a>
</strong>
</div>
To get Listing Title, I have implemented this code:
$page = "http://www.mywebsite.com/listings.html";
$html = new simple_html_dom();
$html->load_file($pagina);
foreach($html->find('.listing_title') as $element)
echo $element->first_child()->plaintext . '<br>';
OUTPUT IS:
Listing Title
Now I need get id value
url_id_1977
preferably only "1977", clean of "url_id_", but I dont know do. Thanks in advance!!

Add this inside of your foreach loop:
echo end(explode('_', $element->find('a', 0)->id));
To get rid of the warning you could assign the id to a variable:
$id = explode('_', $element->find('a', 0)->id);
echo $id[2];
Or, if your anchor's id always starts with url_id_, just use str_replace():
echo str_replace('url_id_', '', $element->find('a', 0)->id);

try this
foreach($html->find('*[class=listing_title] a') as $element)
echo $element->id. '<br>';

Related

separate meta keys on implode

<?php echo strip_tags(stripslashes($row = implode(['meta_keys']))) ?>
all it shows is "meta_keys" as display, and not the info from the database.
I'm trying to get each key individually linked on an <a href=""> tag.
I know I need to array, but any ideas?
$meta_keys = explode(',', $row['meta_keys']);
foreach ($meta_keys as $key) {
echo strip_tags($key) . ' ';
}

DOM not parsing correctly

I have a script which loads items from an XML file, and displays them, so a user can choose which item they want to remove from their file. Here's the PHP:
<?php
global $current_user;
get_currentuserinfo();
$userid= $current_user->ID;
$dom = new DOMDocument;
$dom->load("playlists/$userid.xml");
echo '<div class="styled-select">';
echo '<center><form name="input" action="/remove/removesure.php" method="get">';
echo '<select name="q[]" size="2" multiple>';
$titles = $dom->getElementsByTagName('title');
foreach ($titles as $title) {
echo '<option>'.$title->nodeValue.'</option>';
}
echo '</select>';
echo '<input type="submit" class="submit" value="Remove">';
echo '</form></center>';
echo '</div>';
?>
The problem I've ran into is that it doesn't display some objects correctly, mainly items with hyphens (it displays – instead of -) and titles with spaces at the end, and because of this, my removal code doesn't find the item, and so can't remove it. I don't know what to do, and I don't know why it's doing this. I'm running the code in wordpress, if that makes a difference.
Any ideas?
If there is no chance of having any kind of councurrency, I would suggest you to use the title index of the title tag as value of "option". Eg:
$titles = $dom->getElementsByTagName('title');
$counter = 0;
foreach ($titles as $title) {
echo '<option value='.$counter.' >'.$title->nodeValue.'</option>';
$counter++;
}
In removesure.php, you could handle this by using an XPath expression like the next one:
//Title[2]
where "2" is the index of the title that must be removed.
That is a possible solution; another path you could try to follow is to handle spaces providing the best encoding option for your titles. htmlentity is the function that you should execute
echo '<option>'.htmlentity($title->nodeValue).'</option>'

PHP inserting variable into a link href and name

This is the code I am working with:
<?php
$rss = new DOMDocument();
$rss->load('http://hugeriver.wordpress.com/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('encoded')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = count($feed);
for($x=0;$x<$limit;$x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$description = $feed[$x]['desc'];
$date = date('l F d, Y', strtotime($feed[$x]['date']));
echo '<h2><a name="test">'.$title.'</a><span class="line"></span></h2>';
echo '<small><em>Posted on '.$date.'</em></small></p>';
echo '<p>'.$description.'</p>';
}
?>
I am stuck specifically with this line. I am trying to make it so the title is both the name of the ancor and the link (so when clicked it scrolls to the top). This is what I tried that doesn't work. Can anyone please show me what is wrong with my syntax?
echo '<h2><a name="'.$title'" href="#'.$title'">'.$title.'</a><span class="line"></span></h2>';
You're currently creating a link that targets itself.
If you want the link to go to the top of the document when clicked, simply link to '#':
<?php echo $title ?>
Also, name is deprecated on <a/> elements in HTML 5. Use id instead:
<?php echo $title ?>
Andre answer should solve your problem, if what you want to do is simply go to the top of the page. however if you want to go to a specific section that has id set to the value of $title then you can try this...
<?php echo $title ?>
This way when the link is clicked it will jump to the exact element with ID equal to title(which may or may not be at the top). I believe this is what you want to achieve.
<a href="#" ID="<?php echo htmlentities($title, ENT_QUOTES); ?>">
<?php echo htmlentities($title, ENT_NOQUOTES); ?></a>
Why is everyone forgetting htmlentities(), especially for attributes?
And why use $title as #target? When the $title is a variable with spaces and punctuation unfit for #target practice... Why not use an md5($title) since your generating the page dynamically? Like:
<a href="#" ID="<?php echo htmlentities(md5($title), ENT_QUOTES); ?>">
<?php echo htmlentities($title, ENT_NOQUOTES); ?></a>
and later on linking to it like this:
<a href="#<?php echo htmlentities(md5($title), ENT_QUOTES); ?>">
Go to <?php echo htmlentities($title, ENT_NOQUOTES); ?>!</a>
there are two missing dots.
try this:
echo '<h2><a name="'.$title.'" href="#'.$title.'">'.$title.'</a><span class="line"></span></h2>';
try this syntax
echo "<h2><a name=\"$title\" href=\"#$title\">$title</a><span class=\"line\"></span></h2>";
or
echo "<h2><a name='$title' href='#$title'>$title</a><span class='line'></span></h2>";
This is much cleaner and has less probability of missing a dot or closing/opening quote.
echo '<h2><a name="'.$title.'" href="#'.$title.'">'.$title.'</a><span class="line"></span></h2>';
You are missing dots after $title
Also, your links link to themself. You need to define a seperate anchor and then link to it.

Detailed preg_match_all

I am having an issue getting a detailed preg_match_all to work. I keep getting a blank Array.
Here is my code:
<?php
$remote_search = file_get_contents('http://wiki.seg.org/index.php?title=Special%3ASearch&search=drilling&button=');
preg_match_all('%<li><div class=\'mw-search-result-heading\'>(.*) </div> <div class=\'searchresult\'>(.*)</div>
<div class=\'mw-search-result-data\'>(.*)</div></li>%si', $remote_search, $links);
echo '<ul class=\'mw-search-results\'>';
for($i = 0; $i < count($links[1]); $i++) {
echo '<li><div class=\'mw-search-result-heading\'><a href="' . $links[5][$i] . '" title="' . $links[4][$i] . '">' . $links[3][$i] . '<\/a> </div> <div class=\'searchresult\'>' . $links[2][$i] . '<\/div><div class=\'mw-search-result-data\'>' . $links[1][$i] . '<\/div><\/li>';
}
echo '</ul>';
?>
I am trying to grab the link details from code shown below:
<li><div class='mw-search-result-heading'>Dictionary:Cable drilling </div> <div class='searchresult'>{{lowercase}}{{#category_index:C|cable <span class='searchmatch'>drilling</span>}}
</div>
<div class='mw-search-result-data'>132 B (22 words) - 19:58, 20 December 2011</div></li>
When I perform a var_dump($links); I get Array as the result.
The code below works to grab the contents in the section I am trying to pull the variables.
<?php
$remote_search = file_get_contents('http://wiki.seg.org/index.php?title=Special%3ASearch&search=drilling&button=');
preg_match_all('%<ul class=\'mw-search-results\'>(.*)</ul>%si', $remote_search, $links);
$bar = $links[0];
echo '<ul class=\'mw-search-results\'>';
echo $bar;
echo '</ul>';
var_dump($links);
?>
The echo $bar; results in Array and no ouput.
The var_dump($links); in this snippet outputs the content of the ul.
Does anyone see the error in my top snippet that is preventing me from parsing the code the way I am intending it?
Try:
preg_match_all('#<li><div\s*class=\'mw-search-result-heading\'><a\s*href=.([^"]*).\s*title=.([^"]*).>([^<]*)<\/a>\s*<\/div>\s*<div\s*class=\'searchresult\'>(.*?)<\/div>\s*<div\s*class=.mw-search-result-data.>([^<]*)<\/div><\/li>#sim', $remote_search, $links);
print_r($links);
The logic error in your code was the way you were matching <div class=\'searchresult\'>(.*)</div> against <div class='searchresult'>{{lowercase}}{{#category_index:C|cable <span class='searchmatch'>drilling</span>}}</div>
This doesn't work well with regular expressions since there is a nested tag -- the span. So I changed your matching logic to non-greedy: .*?. Also notice how I changed the flag modifiers for the regular expression to sim. I always use these three modifiers whenever I toss a regular expression against HTML. I use them so often I even found a way to arrange the modifier letters into a word namely "sim" as a memory aid to help remember the modifiers.
Happy coding!
Never try to parse html with Regex. Use DOMDocument instead. In your case to get links from file you can do something like:
$dom = new DOMDocument();
$dom->load($url);
$elements = $dom->getElementsByTagName('a');
$links = array();
foreach ($elements as $element)
$links[] = $element->getAttribute('href');
var_dump($links);

How to rewrite this php function into HTML-emeddable function <?php ?>

Could someone convert this line of code to be readable by HTML?
echo '<h3>'. $r['title'] .'</h3>';
into something like this:
<?php echo...blah blah blah ?> /* To display the title in HTML */
I am sure I am not doing it right, that's why it's still not working :(.
Edit: There seems to be a confusion here. I am not going to modify the original php function. What I need to do is call it to my HTML page, to display the Title of the page
function r($text, $level = 3)
{
$tag = 'h' . $level . '>';
return '<' . $tag . $text . '</' . $tag;
}
Thanks for the downvote. The given question is totally unclear and constantly edited.
Ah you mean?
<php echo "<h3>$r['title']</h3>"; ?>
could be an answer to this unclear question
Save the result into a variable.
<?php $title = '<h3>'. $r['title'] .'</h3>';?>
<?php echo $title; ?>
Not exactly sure what you're asking, but you can't use PHP code within an HTML page.
The line
<?php echo '<h3>'. $r['title'] .'</h3>'; ?>
Within a PHP file, will print out the contents of $r['title'], within <h3> tags.
There is no function involved; $r is an associative array variable and title is a key to a particular value.

Categories