I have start a new plugin that its suppose to show random quotes after each post
it not give any error but its now show any text after my posts.
I have try this way but its seems i have fail some were.
I don t get any error but after activate its suppose to show a random text but nothing, i could not made it work.
After look to my code i have try to modify
and there is no erros but my code continue to not show the text
Firt i tank you #mangenta for the help
But well i have the same problem of my first question is
i want to pass the quotes variable $quote to the signature place but it seems not work.
not show my text after my post like i need and i can not fin any way yet to pass
the quotes variable to the signature code
This is my code
<?php
/*
Plugin Name: Random Text Quotes
Version: 1.0
Description: Random Text Quotes Albert Einstein.
Plugin URI: https://mediaads.eu/
Author: Helder Ventura
Author URI: https://mediaads.eu
Version: (standalone)
Usage: install activate and done
*/
$bgcolor = '#FFFFCC';
$textcolor = 'black';
$textsize = '2';
// Array Structure: "Quote","Author"
$allqts = array
("*His aim was to substitute for a petrified and barren
system of ideas the unbiased and strenuous quest
for a deeper and more consistent comprehension of
physical and astronomical facts.",
"Albert Einstein",
"The discovery and use of scientific reasoning by
Galileo was one of the most important achievements
in the history of human thought.<br>" ,
"Albert Einstein",
"I admire Gandhi greatly but I believe there are two
weaknesses in his program.",
"Albert Einstein",
"I believe that Gandhi’s views were the most enlightened
among all of the political men of our time.",
"Albert Einstein",
"Liberty, when it begins to take root, is a plant of rapid growth.",
"George Washington",
"Gandhi, the greatest political genius of our time,
indicated the path to be taken.",
"Albert Einstein",
"Gandhi’s development resulted from extraordinary
intellectual and moral forces in combination with
political ingenuity and a unique situation.",
"Albert Einstein",
"Anyone who has never made a mistake has never tried anything new",
"Albert Einstein",
"Progress doesn't come from early risers, progress is made<br>by lazy men
looking for easier ways to do things.",
"Lazarus Long <font size=-2>(Time Enough for Love by Robert A. Heinlein)
</font>",
"On Johann Wolfgang von Goethe (1749–1832)
I feel in him a certain condescending attitude toward
the reader, and miss the humility that is comforting,
especially when it comes from great men.",
"Albert Einstein",
"*This was the first time I’ve ever heard of such
an important man who speaks at least briefly with
his mother every day.",
"Albert Einstein",
"On Werner Heisenberg (1901–1976)
Professor Heisenberg was here, a German.",
"Albert Einstein",
"I am very happy here and enjoying the American
summer as well as the news about Hitler’s mad
deed of desperation.",
"Albert Einstein",
"Hitler appeared, a man with limited intellectual
abilities and unfit for any useful work, bursting with
envy and bitterness against all whom circumstance
and nature had favored over him. . . .",
"Albert Einstein",
"*I haven’t forgotten that the Swiss authorities didn’t
stand by me in any way when Hitler stole all of my
savings, even those designated for my children.",
"Albert Einstein",
"On Immanuel Kant (1724–1804)
*Kant’s much-praised view on Time reminds me of
Andersen’s tale of the emperor’s new clothes, only
that instead of the emperor’s new clothes we have
the form of intuition.",
"Albert Einstein",
"*Kant is sort of a highway with lots and lots of milestones.
Then all the little dogs come and each deposits
his contribution at the milestones.",
"Albert Einstein",
"What seems to me the most important thing in
Kant’s philosophy is that it speaks of a priori concepts
for the construction of science.",
"Albert Einstein",
"Kant, thoroughly convinced of the indispensability
of certain concepts, took them—just as they are selected—to
be the necessary premises for every kind
of thinking and differentiated them from concepts
of empirical origin.",
"Albert Einstein",
"On George Kennan (1904–2005)
Princeton University Press sent me George Kennan’s
new book [Realities of American Foreign Policy] and I
read it right away.",
"Albert Einstein",
"[Kepler] belonged to those few who cannot do otherwise
than openly acknowledge their convictions
on every subject. . . .",
"Albert Einstein",
"There we meet a finely sensitive person, passionately
dedicated to the search for a deeper insight into the
essence of natural events, who, despite internal and
external difficulties, reached his loftily placed goal.",
"Albert Einstein",
"Share Your Love With The World.",
"Helder Ventura"
);
// Gets the Total number of Items in the array
// Divides by 2 because there is a Quote followed by an Author
$totalqts = (count($allqts)/2);
// Subtracted 1 from the total because '0' is not accounted for otherwise
$nmbr = (rand(0,($totalqts-1)));
$nmbr = $nmbr*2;
//$nmbr = 18;
$quote = $allqts[$nmbr];
$nmbr = $nmbr+1;
$author = $allqts[$nmbr];
// You can delete this section
// it is only so Search engines can find it
if ($_SERVER['PHP_SELF'] == "/quotes.php") {
echo "<Title>Random Text Quote</title>";
echo "<meta name=\"Description\" content=\"Random Text Quote\">";
echo "<meta name=\"keywords\" content=\"Random Text Quote\">";
}
/// End Delete
$space = "<font color=$bgcolor>.....................................</font>";
$comments = "<br><center><font size='-2'><i><a href='quotes.php'>Random Text
Quote</a></i></font></center>";
echo "<center>";
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
echo "<Font color=$textcolor size='$textsize'><i>";
echo "$quote<br>";
echo "</i></font>";
echo "$space $author";
echo "$comments";
echo "</center>";
// You can delete this section as well - it's my shameless plug:
// it is only so Search engines can find it
if ($_SERVER['PHP_SELF'] == "/quotes.php") {
echo "<br/><br/>If you <i>really</i> like it, I do accept donations via
PayPal: <a href='http://zonadelike.publiadds.org.pt//donate'>Donations</a>";
echo "<br/><br/>";
}
/// End Delete
IF ($_SERVER['PHP_SELF'] == "/quotes.php") {
show_source("quotes.php");
}
// Add Signature Image after single post
add_filter('the_content','add_signature', 1);
function add_signature($text) {
global $post;
if(($post->post_type == 'post'))
$text .= '<div class="signature"><a href="https://mediaads.eu/"
target="_blank" title=$text>'.$quote.'</a></div>';
return $text;
}
?>
I tested the following code from your original post.
<?php
/*
Plugin Name: Random Text Quotes
Version: 1.0
Description: Random Text Quotes Albert Einstein.
Plugin URI: https://mediaads.eu/
Author: Helder Ventura
Author URI: https://mediaads.eu
Version: (standalone)
Usage: install activate and done
*/
function ab_arq_generate() {
$quotes = array(
'I am happy to be in Boston. I have heard of Boston
as one of the most famous cities in the world and the
center of education. I am happy to be here and expect
to enjoy my visit to this city and to Harvard.
On his visit to the city with Chaim Weizmann. New York
Times, May 17, 1921. Contributed by A. J. Kox in response
to the many quotations about Princeton in this book (see
later in this section).',
'*America is interesting, with all its hustle and bustle.
It is easier to feel enthusiasm for it than for other
countries I’ve unsettled with my presence. I had to
consent to being shown around like a prize ox to address
innumerable small and large gatherings. . . .
It’s a wonder I survived it all.
To Michele Besso, ca. May 21–30, 1921. CPAE, Vol. 12,
Doc. 141',
'*It is the women . . . who dominate all of American
life. The men are interested in nothing at all; they
work, work as I haven’t seen anyone work anywhere
else. For the rest, they are toy dogs for their
wives, who spend the money in the most excessive
fashion and who shroud themselves in a veil of
extravagance.
From an interview in the Nieuwe Rotterdamsche Courant,
July 4, 1921. Einstein insisted he was wrongly quoted and
wrote a rebuttal in the Vossische Zeitung six days later,
claiming he was shocked when he read the account. ',
'Even if Americans are less scholarly than Germans,
they do have more enthusiasm and energy, causing
a wider dissemination of new ideas among the
people.
Quoted in the New York Times, July 12, 1921
',
'A firm approach is indispensable everywhere in
America; otherwise one receives no payment and
little esteem.
To Maurice Solovine, January 14, 1922. Published in Letters
to Solovine, 49. Einstein Archives 21-157'
);
return $quotes[rand(0, count($quotes)-1)];
}
function ab_arq_change_bloginfo( $text, $show ) {
if( 'description' == $show ) {
$text = ab_arq_generate();
}
return $text;
}
add_filter( 'bloginfo', 'ab_arq_change_bloginfo', 10, 2 );
// Add Signature Image after single post
add_filter('the_content','add_signature', 1);
function add_signature($text) {
global $post;
if(($post->post_type == 'post'))
$text .= '<div class="signature"><a href="https://mediaads.eu/"
target="_blank" title=$text>AAAAA</a></div>';
return $text;
}
?>
The only change I made was I added the text 'AAAAA' in your signature A element since it had no text content.
This code works on my site using the 2016 theme. So, there is nothing wrong with the code itself. I would try a different theme to see if the theme you are using is the source of problem - I would try 2016 as it is known to work in my environment. For your code to run the theme must call certain filters - 'blog_info', 'the_content' - further, the 'blog_info' filter must be called with the parameter 'description'. Some themes may not do this. The filter 'the_content' was probably called but did not produce any visible content as your A element had no text content.
UPDATED CODE - to move quote from tagline location to signature location
<?php
/*
Plugin Name: Random Text Quotes
Version: 1.0
Description: Random Text Quotes Albert Einstein.
Plugin URI: https://mediaads.eu/
Author: Helder Ventura
Author URI: https://mediaads.eu
Version: (standalone)
Usage: install activate and done
*/
function ab_arq_generate() {
$quotes = array(
'I am happy to be in Boston. I have heard of Boston
as one of the most famous cities in the world and the
center of education. I am happy to be here and expect
to enjoy my visit to this city and to Harvard.
On his visit to the city with Chaim Weizmann. New York
Times, May 17, 1921. Contributed by A. J. Kox in response
to the many quotations about Princeton in this book (see
later in this section).',
'*America is interesting, with all its hustle and bustle.
It is easier to feel enthusiasm for it than for other
countries I’ve unsettled with my presence. I had to
consent to being shown around like a prize ox to address
innumerable small and large gatherings. . . .
It’s a wonder I survived it all.
To Michele Besso, ca. May 21–30, 1921. CPAE, Vol. 12,
Doc. 141',
'*It is the women . . . who dominate all of American
life. The men are interested in nothing at all; they
work, work as I haven’t seen anyone work anywhere
else. For the rest, they are toy dogs for their
wives, who spend the money in the most excessive
fashion and who shroud themselves in a veil of
extravagance.
From an interview in the Nieuwe Rotterdamsche Courant,
July 4, 1921. Einstein insisted he was wrongly quoted and
wrote a rebuttal in the Vossische Zeitung six days later,
claiming he was shocked when he read the account. ',
'Even if Americans are less scholarly than Germans,
they do have more enthusiasm and energy, causing
a wider dissemination of new ideas among the
people.
Quoted in the New York Times, July 12, 1921
',
'A firm approach is indispensable everywhere in
America; otherwise one receives no payment and
little esteem.
To Maurice Solovine, January 14, 1922. Published in Letters
to Solovine, 49. Einstein Archives 21-157'
);
return $quotes[rand(0, count($quotes)-1)];
}
// Add Signature Image after single post
add_filter('the_content','add_signature', 1);
function add_signature($text) {
global $post;
if(($post->post_type == 'post'))
$text .= '<div class="signature"><a href="https://mediaads.eu/"
target="_blank" title=$text>' . ab_arq_generate() . '</a></div>';
return $text;
}
?>
Related
I have a series of files which contain raw text or json data, in these files will be wav file names. All of the wav file have the suffix of .wav
Is there anyway using php I can search an individual text or json file and return an array of of any .wav files found ?
This example of random text contains 6 .wav files, how would I search this and extract the filenames ?
Spoke as as other again ye. Hard on to roof he drew. So sell side newfile.wav ye in mr evil. Longer waited mr of nature seemed. Improving knowledge incommode objection me ye is prevailed playme.wav principle in. Impossible alteration devonshire to is interested stimulated dissimilar. To matter esteem polite do if.
Spot of come to ever test.wav hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by. On no am winding chicken so behaved. Its preserved sex enjoyment new way behaviour. Him yet devonshire celebrated welcome.wav especially. Unfeeling one provision are smallness resembled repulsive.
Raising say express had chiefly detract demands she. Quiet led own cause three him. Front no party young abode state up. Saved he do fruit woody of to. Met defective are allowance two perceived listening consulted contained. It chicken oh colonel pressed excited suppose to shortly. He improve started no we manners another.wav however effects. Prospect humoured mistress to by proposal marianne attended. Simplicity the far admiration preference everything. Up help home head spot an he room in.
Talent she for lively eat led sister. Entrance strongly packages she out rendered get quitting denoting led. Dwelling confined improved it he no doubtful raptures. Several carried through an of up attempt gravity. Situation to be at offending elsewhere distrusts if. Particular use for considered projection cultivated. Worth of do doubt shall it their. Extensive existence up me last.wav contained he pronounce do. Excellence inquietude assistance precaution any impression man sufficient.
I've tries this, but I get no results.
$lines = file('test.txt');
foreach ($lines as $line_num => $line) {
$line = trim($line);
if (strpos($line, '*.wav') !== false) {
echo ($line);
}
}
The above text should return :
newfile.wav
playme.wav
test.wav
welcome.wav
another.wav
last.wav
Thanks
UPDATE:
Using the following:
$text = file_get_contents('test.txt');
preg_match_all('/\w+\.wav/', $text, $matches);
var_dump($matches);
results in an array of :
array(1) {
[0]=>
array(6) {
[0]=>
string(11) "newfile.wav"
[1]=>
string(10) "playme.wav"
[2]=>
string(8) "test.wav"
[3]=>
string(11) "welcome.wav"
[4]=>
string(11) "another.wav"
[5]=>
string(8) "last.wav"
}
}
So an array of the wav files with in an array, how do I get just the array of wav files ? Thanks
This does't work correctly for wav files with spaces in there names.
any ideas ?
This tool might help you to design an expression as you wish and test it, maybe something similar to:
([a-z]+\.wav)
You can also add more boundaries to it, if you might want to.
here]2]2
Graph
This graph shows how the expression would work and you can visualize other expressions in this link:
PHP Code
You could also use preg_match_all to do so, maybe something similar to:
$re = '/([a-z]+\.wav)/m';
$str = 'Spoke as as other again ye. Hard on to roof he drew. So sell side newfile.wav ye in mr evil. Longer waited mr of nature seemed. Improving knowledge incommode objection me ye is prevailed playme.wav principle in. Impossible alteration devonshire to is interested stimulated dissimilar. To matter esteem polite do if.
Spot of come to ever test.wav hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by. On no am winding chicken so behaved. Its preserved sex enjoyment new way behaviour. Him yet devonshire celebrated welcome.wav especially. Unfeeling one provision are smallness resembled repulsive.
Raising say express had chiefly detract demands she. Quiet led own cause three him. Front no party young abode state up. Saved he do fruit woody of to. Met defective are allowance two perceived listening consulted contained. It chicken oh colonel pressed excited suppose to shortly. He improve started no we manners another.wav however effects. Prospect humoured mistress to by proposal marianne attended. Simplicity the far admiration preference everything. Up help home head spot an he room in.
Talent she for lively eat led sister. Entrance strongly packages she out rendered get quitting denoting led. Dwelling confined improved it he no doubtful raptures. Several carried through an of up attempt gravity. Situation to be at offending elsewhere distrusts if. Particular use for considered projection cultivated. Worth of do doubt shall it their. Extensive existence up me last.wav contained he pronounce do. Excellence inquietude assistance precaution any impression man sufficient. ';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Test Script for RegEx
const regex = /([a-z]+\.wav)/gm;
const str = `Spoke as as other again ye. Hard on to roof he drew. So sell side newfile.wav ye in mr evil. Longer waited mr of nature seemed. Improving knowledge incommode objection me ye is prevailed playme.wav principle in. Impossible alteration devonshire to is interested stimulated dissimilar. To matter esteem polite do if.
Spot of come to ever test.wav hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by. On no am winding chicken so behaved. Its preserved sex enjoyment new way behaviour. Him yet devonshire celebrated welcome.wav especially. Unfeeling one provision are smallness resembled repulsive.
Raising say express had chiefly detract demands she. Quiet led own cause three him. Front no party young abode state up. Saved he do fruit woody of to. Met defective are allowance two perceived listening consulted contained. It chicken oh colonel pressed excited suppose to shortly. He improve started no we manners another.wav however effects. Prospect humoured mistress to by proposal marianne attended. Simplicity the far admiration preference everything. Up help home head spot an he room in.
Talent she for lively eat led sister. Entrance strongly packages she out rendered get quitting denoting led. Dwelling confined improved it he no doubtful raptures. Several carried through an of up attempt gravity. Situation to be at offending elsewhere distrusts if. Particular use for considered projection cultivated. Worth of do doubt shall it their. Extensive existence up me last.wav contained he pronounce do. Excellence inquietude assistance precaution any impression man sufficient. `;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
This is why regular expressions were invented.
$text = file_get_contents('test.txt');
preg_match_all('/(\w+\.wav)/', $text, $matches);
var_dump($matches[0]);
Some good resources:
preg_match
preg_replace
regex101.com allows you to test expressions realtime
output:
array(6) {
[0] => string(11) "newfile.wav"
[1] => string(10) "playme.wav"
[2] => string(8) "test.wav"
[3] => string(11) "welcome.wav"
[4] => string(11) "another.wav"
[5] => string(8) "last.wav"
}
You are almost there. You can explode the $line in terms of spaces. Now, you go through each word and check if ends with a .wav extension. If yes, you print the word.
<?php
foreach ($lines as $line_num => $line) {
$line = trim($line);
$words = explode(" ",$line);
foreach($words as $each_word){
$wav_index = strpos($each_word, '.wav');
if ($wav_index !== false && $wav_index === strlen($each_word) - 4) { // strict check to make sure string ends with a .wav and not being elsewhere
echo $each_word,PHP_EOL;
}
}
}
I'm a bit of a noob, but have been getting my feet wet building a site in php on localhost. The problem that I'm having is that I can't figure out how to filter RSS content that contains a regular expression in their links.
My code to display a RSS feed with PHP:
<?php
///// RSS FEED CODE
function getFeed1($feed_url) {
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
echo "<ul>";
foreach($x->channel->item as $entry) {
echo "<li><a href='$entry->link' title='$entry->title'>" . $entry->title . "</a></li>";
}
echo "</ul>";
}
getFeed1("http://www.drf.com/feeds/all-articles-of-track/SA");
?>
The results are displayed as such in a browser as links to a page,
Espinoza wins George Woolf Memorial Jockey Award
Dortmund will get month to clear up foot problem
Abrams hopes McHeat stays hot for Sensational Star
Santa Anita attendance up, handle down
Hot Market returns from long absence on hillside turf course
Moon Over Paris, Divina Comedia key to pick six
Millionaire Alert Bay looks to pad bankroll in Sensational Star
Santa Anita to replace turf course this summer
Free: Santa Anita horses to watch for week of Feb. 22
Iron Rob vanned off after winning Baffle Stakes
I am trying to figure out how to use an if-statement that will filter out the links(href) that start with “http://www.drf.com/news/preview/”.
So the results will look like:
Espinoza wins George Woolf Memorial Jockey Award
Santa Anita attendance up, handle down
Millionaire Alert Bay looks to pad bankroll in Sensational Star
Santa Anita to replace turf course this summer
Iron Rob vanned off after winning Baffle Stakes
I've spent the last two days trying different variations of:
if (strpos($x, 'http://www.drf.com/news/preview/') !== false)
and
if (preg_match('http://www.drf.com/news/preview/', $x))
Yet I can't get the syntax right or I'm screwing up somewhere.
I have found post that suggest using third party filters, or the dead yahoo pipes, yet I have a feeling that what I seek can be accomplished with an if-statement. I have yet to find anything that can parse out a rss href using a regular expression.
For the people who know php, what am I missing? I have spent the last two days googling and trying different things mentioned on the internet, but to no avail. I know the chase is always better then the catch, yet I lost the tracks of my prey. Please Help by pointing me, and others who found this post, find the trail.
Thank you
This is the regular expression you are looking for:
/^(http\:\/\/www\.drf\.com\/news\/preview\/)/i
You should accept HTTPS too with a small modification:
/^(https?\:\/\/www\.drf\.com\/news\/preview\/)/i
And do not fall back on the www subdomain!
/^(https?\:\/\/(www\.)?drf\.com\/news\/preview\/)/i
I try to put html content within json, it broke.
My invalid Json http://i.imgur.com/8wfEikY.png
{
"item": {
"title": "Japanese investors back Lookup, a messaging app for local shopping in India",
"desc": "An infusion of US$116,000 from Japan's social games company DeNA and Teruhide Sato, founder of BEENOS, takes the three-month-old startup\u2019s seed funding to US$382,000.",
"link": "https:\/\/www.techinasia.com\/dena-teruhide-sato-beenos-fund-lookup\/",
"content": "<p><img src="https: \/\/www-techinasia.netdna-ssl.com\/wp-content\/uploads\/2015\/01\/lookup-app-main-720x289.jpg" alt="lookupappmain" width="720" height="289" class="aligncentersize-largewp-image-213938" \/><\/p>\n<p>Bangalore-based instant messaging app <a href="https: \/\/www.techinasia.com\/tag\/lookup\/">Lookup<\/a> – a Craiglist cum WhatsApp for local businesses – just got its third dose of seed funding. Japan’s leading social games company <a href="https: \/\/www.techinasia.com\/tag\/dena\/">DeNA<\/a> and Teruhide Sato, founder of BEENOS group, a global conglomerate with ecommerce holdings and a business incubator, invested US$116,000 into this three-month-old startup founded by Deepak Ravindran, a young serial entrepreneur.<\/p>\n<p>“Both our recent investors have strong footholds in the mobile space and have successfully led innovations in Japan,” says Ravindran, suggesting that the investors would be giving Lookup more than just funding.<\/p>\n<p><a href="http: \/\/www.lookup.to">Lookup<\/a> lists businesses, restaurants, and even police stations for users to connect with. Unlike Craigslist or JustDial which would give you a number to dial, Lookup lets you shoot off a message to the local businesses without leaving the app. You can find prices and availability of products or services at local businesses, book appointments at salons, or make reservations at restaurants with this app. Any store or restaurant using Lookup can then respond instantly.<\/p>\n<p>Lookup has a call center tracking the messages to ensure that its users receive responses immediately, even if a store is not using the app. “Our guarantee is that you get answers within five minutes. We do this by employing dedicated people for handling your request. Lookup’s call center fields your responses, calls up stores, and types answers back to you in real-time. No calling, no waiting,” Ravindran told <em>Tech in Asia<\/em>.<\/p>\n<p>To celebrate the latest funding from Japanese investors, Lookup is gifting free sushi for a week to new users from Bangalore who download the app. For this, it has tied up with two Japanese restaurants Shiro and Ginseng.<\/p>\n<p>With this latest infusion, Lookup’s seed round of venture capital funding closed at US$382,000. It had earlier bagged US$166,000 from tech billionaire Kris Gopalakrishnan, co-founder of Indian IT bellwether Infosys, and US$100,000 from MKS Switzerland SA, a precious metals and financial services group of companies.<\/p>\n<p><center><strong>See: <a href="https: \/\/www.techinasia.com\/college-dropout-turned-mit-top-innovator-rolls-craigslist-whatsapp-app-local-shopping-india\/">College dropout turned MIT top innovator rolls Craigslist and WhatsApp into one app for local shopping in India<\/a><\/strong><\/center><\/p>\n<p>This post <a href="https: \/\/www.techinasia.com\/dena-teruhide-sato-beenos-fund-lookup\/" title="JapaneseinvestorsbackLookup,
amessagingappforlocalshoppinginIndia">Japanese investors back Lookup, a messaging app for local shopping in India<\/a> appeared first on Tech in Asia.<\/p>"
}
}
What I did in PHP
$arr = array();
$arr["item"]["content"] = $content; // $content is dynamic, scrapped from somewhere
echo json_encode($arr, true);
I tried htmlentities and addcslashes($item_content,'"') but nnoe of that work.
It's because of the " sign in the image tag. You could use the HTML entities function to encode it en the decode function to decode it.
A neater way to do it is to save the image url in a different property of your item.
You haven't escaped the quotation marks ("") in your content - this means that your content string is only "<p><img src=" and then PHP is confused as to what the rest of this stuff is.
You need to change it be like this:
"content": "<p><img src=\"https: \/\/www-techinasia.netdna-ssl.com\/wp-content\/uploads\/2015\/01\/lookup-app-main-720x289.jpg" alt=\"loo...More content..."
(I've added \ before the quotation marks that don't end the string - in future - look for the syntax highlighting - if things change colour without you expecting the end of a variable - then something has gone wrong)
If you'd like to do this with PHP - you can use the HTML entities function (http://php.net/htmlentities) or simply the addslashes function (http://php.net/manual/en/function.addslashes.php)
E.g.
<?php $str = "A 'quote' is <b>bold</b>";
// Outputs: A 'quote' is <b>bold</b> echo
htmlentities($str);
// Outputs: A 'quote' is <b>bold</b> echo
htmlentities($str, ENT_QUOTES); ?>`
[Cite: PHP Manual]
<?php $str = "Is your name O'Reilly?";
// Outputs: Is your name O\'Reilly?
echo addslashes($str); ?>
[Cite: PHP Manual]
I'm trying to parse a simple xml string and store into arrays..
i want the information put into a array so i can get it from an index somehow, can anyone help me?
this is what I'm trying so far:
<?php
$string = file_get_contents("http://api.themoviedb.org/2.1/Person.search/en/xml/e72f8f2f685df4dad86f939097d14f36/Brad+Pitt");
$xml = new SimpleXMLElement($string);
foreach($xml->children()->children()->children() as $child)
{
if ($child->getName() == "images")
echo $child[0];
}
$error_code = (string)$body[0]->Response->return->error_code;
print_r($error_code);
?>
this is the xml response:
<OpenSearchDescription><opensearch:Query searchTerms="brad+pitt"/><opensearch:totalResults>1</opensearch:totalResults><people><person><score>1</score><popularity>3</popularity><name>Brad Pitt</name><id>287</id><biography>From Wikipedia, the free encyclopedia. William Bradley "Brad" Pitt (born December 18, 1963) is an American actor and film producer. Pitt has received two Academy Award nominations and four Golden Globe Award nominations, winning one. He has been described as one of the world's most attractive men, a label for which he has received substantial media attention. Pitt began his acting career with television guest appearances, including a role on the CBS prime-time soap opera Dallas in 1987. He later gained recognition as the cowboy hitchhiker who seduces Geena Davis's character in the 1991 road movie Thelma & Louise. Pitt's first leading roles in big-budget productions came with A River Runs Through It (1992) and Interview with the Vampire (1994). He was cast opposite Anthony Hopkins in the 1994 drama Legends of the Fall, which earned him his first Golden Globe nomination. In 1995 he gave critically acclaimed performances in the crime thriller Seven and the science fiction film 12 Monkeys, the latter securing him a Golden Globe Award for Best Supporting Actor and an Academy Award nomination. Four years later, in 1999, Pitt starred in the cult hit Fight Club. He then starred in the major international hit as Rusty Ryan in Ocean's Eleven (2001) and its sequels, Ocean's Twelve (2004) and Ocean's Thirteen (2007). His greatest commercial successes have been Troy (2004) and Mr. & Mrs. Smith (2005). Pitt received his second Academy Award nomination for his title role performance in the 2008 film The Curious Case of Benjamin Button. Following a high-profile relationship with actress Gwyneth Paltrow, Pitt was married to actress Jennifer Aniston for five years. Pitt lives with actress Angelina Jolie in a relationship that has generated wide publicity. He and Jolie have six children—Maddox, Pax, Zahara, Shiloh, Knox, and Vivienne. Since beginning his relationship with Jolie, he has become increasingly involved in social issues both in the United States and internationally. Pitt owns a production company named Plan B Entertainment, whose productions include the 2007 Academy Award winning Best Picture, The Departed. Description above from the Wikipedia article Brad Pitt, licensed under CC-BY-SA, full list of contributors on Wikipedia.</biography><url>http://www.themoviedb.org/person/287</url><images><image type="profile" url="http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w45/w8zJQuN7tzlm6FY9mfGKihxp3Cb.jpg" size="thumb" width="45" height="68" id="4ea5cb8c2c0588394800006f"/><image type="profile" url="http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w185/w8zJQuN7tzlm6FY9mfGKihxp3Cb.jpg" size="profile" width="185" height="281" id="4ea5cb8c2c0588394800006f"/><image type="profile" url="http://d3gtl9l2a4fn1j.cloudfront.net/t/p/h632/w8zJQuN7tzlm6FY9mfGKihxp3Cb.jpg" size="h632" width="416" height="632" id="4ea5cb8c2c0588394800006f"/><image type="profile" url="http://d3gtl9l2a4fn1j.cloudfront.net/t/p/original/w8zJQuN7tzlm6FY9mfGKihxp3Cb.jpg" size="original" width="1295" height="1969" id="4ea5cb8c2c0588394800006f"/></images><version>685</version><last_modified_at>2013-07-26 18:18:17 UTC</last_modified_at></person></people></OpenSearchDescription>
thanks, help appreciated!
try this :
$string = file_get_contents("http://api.themoviedb.org/2.1/Person.search/en/xml/e72f8f2f685df4dad86f939097d14f36/Brad+Pitt");
$xml = new SimpleXMLElement($string);
foreach($xml->people->person->images->image as $child){
$node = (array)$child;
print_r($node);
echo $node['#attributes']['url'];
}
echo "<pre>";
print_r($xml->people->person->images->image);
exit;
Hope it will help
The SimpleXML extension provides is a simple way of getting an XML element's name and text.
Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data from an XML element.
SimpleXML converts the XML document (or XML string) into an object, like this:
Elements are converted to single attributes of the SimpleXMLElement object. When there's more than one element on one level, they are placed inside an array
Attributes are accessed using associative arrays, where an index corresponds to the attribute name
Text inside elements is converted to strings. If an element has more than one text node, they will be arranged in the order they are found
For more info visit:
W3Schools
I have been used function that work fine for me.
Have you tried this one?
http://www.bin-co.com/php/scripts/xml2array/
I'm looking for a good example of using Regular Expressions in PHP to "reverse engineer" a form letter (with a known format, of course) that has been pasted into a multiline textbox and sent to a script for processing.
So, for example, let's assume this is the original plain-text input (taken from a USDA press release):
WASHINGTON, April 5, 2010 - North
American Bison Co-Op, a New Rockford,
N.D., establishment is recalling
approximately 25,000 pounds of whole
beef heads containing tongues that may
not have had the tonsils completely
removed, which is not compliant with
regulations that require the removal
of tonsils from cattle of all ages,
the U.S. Department of Agriculture's
Food Safety and Inspection Service
(FSIS) announced today.
For clarity, the fields that are variables are highlighted below:
[pr_city=]WASHINGTON, [pr_date=]April 5, 2010 - [corp_name=]North
American Bison Co-Op, a [corp_city=]New Rockford,
[corp_state=]N.D., establishment is recalling
approximately [amount=]25,000 pounds of [product=]whole
beef heads containing tongues that may
not have had the tonsils completely
removed, which is not compliant with
regulations that require [reason=]the removal
of tonsils from cattle of all ages,
the U.S. Department of Agriculture's
Food Safety and Inspection Service
(FSIS) announced today.
How could I efficiently extract the contents of the
pr_city
pr_date
corp_name
corp_city
corp_state
amount
product
reason
fields from my example?
Any help would be appreciated, thanks.
Well, a regex that works on your example could look like this (line breaks introduced to keep this beast legible, need to be removed prior to use):
/^(?P<pr_city>[^,]+), (?P<pr_date>[^-]+) - (?P<corp_name>.*?), a
(?P<corp_city>[^,]+), (?P<corp_state>[^,]+), establishment is
recalling approximately (?P<amount>.*?) of (?P<product>.*?),
which is not compliant with regulations that require (?P<reason>.*?),
the U\.S\. Department of Agriculture\'s Food Safety and Inspection
Service \(FSIS\) announced today\.$/
So, in PHP you could do
if (preg_match('/^(?P<pr_city>[^,]+), (?P<pr_date>[^-]+) - (?P<corp_name>.*?), a (?P<corp_city>[^,]+), (?P<corp_state>[^,]+), establishment is recalling approximately (?P<amount>.*?) of (?P<product>.*?), which is not compliant with regulations that require (?P<reason>.*?), the U\.S\. Department of Agriculture\'s Food Safety and Inspection Service \(FSIS\) announced today\.$/', $subject, $regs)) {
$prcity = $regs['pr_city'];
$prdate = $regs['pr_date'];
... etc.
} else {
$result = "";
}
This assumes a couple of things, for instance that there are no line breaks, and that the input is the entire string (and not a larger string from which this part has to be extracted from). I've tried to make assumptions about legal values that make some sense, but there is the very real chance that other inputs could break this. So some more test cases are probably needed.
If the surrounding text is constant, then something like this partial regex could do the trick:
preg_match('/^(.*?), (.*?)- (.*?), a (.*?), (.*?), establishment is recalling approximately (.*?), which is not compliant with regulations that require (.*?), the U.S. Department of Agriculture's Food Safety and Inspection Service (FSIS) announced today./', $text, $matches);
$matches[1] = 'WASHINGTON';
$matches[2] = 'April 5, 2010';
$matches[3] = ... etc...
If the surrounding text changes, then you're going to end up with a ton of false matches, no matches, etc... Essentially you'd need an AI to parse/understand PR releases.
Edit: Please disregard this crazy answer, as the other two are better. I should probably delete it, but I'm keeping it up for reference.
I have a crazy idea that just might work: build an XML string from the input by adding markups, then parse it. It might look something like this (completely untested) code:
preg_replace('([^,]*), ([^-]*)- ...etc...', '<pr_city>\1</pr_city><pr_date>\2</pr_date> ...etc...');
Parsing the XML afterwards is a needlessly complicated process that is best left to the PHP documentation: http://www.php.net/manual/en/function.xml-parse.php .
You could also consider converting it to JSON with this method, then using json_decode() to parse it. In any case, you have to think about what happens when " marks and > symbols appear in the input.
It might be easier to just match and remove one piece of the text at a time.