Capitalize title selectively - php

I have a list of headings entered like below:
junior suite for sale
Beautiful eCommerce office
d'Landon Property for rent
stunning House FOR SALE
To make things consistent, we apply text-transform: capitalize to the titles, so that the front-end view would be consistent:
Junior Suite For Sale
Beautiful ECommerce Office
D'Landon Property For Rent
Stunning House For Sale
However, this results in some incorrect names like eCommerce, d'Landon, which is not desirable. Is there anyway to fix this, hopefully without relying on backend logic change (I use PHP by the way)?
Expected result:
Junior Suite For Sale
Beautiful eCommerce Office
d'Landon Property For Rent
Stunning House For Sale

There is no way to do this in CSS alone, but in case javascript is an option as mentioned in my comment, here is a snippet:
let pList = document.getElementsByTagName('h2');
let blackList = /eCommerce|d'Landon/g
for(let i=0; i< pList.length; i++) {
let text = pList[i].textContent;
let newText = text.replace(blackList, '<span class="no-cap">$&<span>');
pList[i].innerHTML = newText;
}
h2 {
text-transform: capitalize;
}
.no-cap {
text-transform: none;
}
<h2>junior suite for sale</h2>
<h2>Beautiful eCommerce office</h2>
<h2>d'Landon Property for rent</h2>
<h2>stunning House FOR SALE</h2>

This is how I would do it in PHP. I would write a bunch of regular expressions to figure out which ones are not the way I want. Then replace the ones I don't want with uppercase and lowercase.
Here for example, in the code below, if all the letters are capital in a word, it is converted. If there are any small letters after the first letter in a word, it isn't converted.
<?php
$titles = ["junior suite for sale",
"Beautiful eCommerce office",
"d'Landon Property for rent",
"stunning House FOR SALE"];
function smart_title($title){
$newtitle = [];
foreach(preg_split("/ /", $title) as $word){
if(preg_match("/^[A-Z]+$/", substr($word, 1, strlen($word)))){
array_push($newtitle, strtoupper(substr($word, 0, 1)).strtolower(substr($word, 1, strlen($word))));
}else if(preg_match("/[A-Z]/", substr($word, 1, strlen($word)))){
array_push($newtitle, $word);
}else{
array_push($newtitle, strtoupper(substr($word, 0, 1)).strtolower(substr($word, 1, strlen($word))));
}
}
return join(" ", $newtitle);
}
foreach($titles as $title){
echo smart_title($title)."\n";
}
?>
Try it out here: http://sandbox.onlinephpfunctions.com/code/450141f600bb5497b46e48b4f96738e811cd3617 .
Result is:
Junior Suite For Sale
Beautiful eCommerce Office
d'Landon Property For Rent
Stunning House For Sale

Related

Apply a design pattern to solve this problem and not use if/else

I am trying to improve my skills with design patterns, so please be easy on me :) In my university I often have to deal with problems where the algorithm is defined, but data structures it is working on are different.
I have the following problem:
If the client is under 18, reduce the base price by 10%.
If the city is ‘London’ the price of the product is 1$.
If the client has a membership type of ‘gold’ the product is free
(£0).
so I tried this:
if($customer <18) {
$price = $price-10;
}
if($city == "London") {
$price = 1;
}
if($client->membership == "gold") {
$price = 0;
}
How can I make it in a nice pattern, like Factory or Strategy? Are they the right one? If not could you tell me which one and give me an example?

How to spit out a headline, photo(s) and story from news article using PHP

Ok so I am fairly lost and frustrated, I've been reading and working on this for hours and when I feel like I make progress...I find out I really haven't.
Problem:Take a news article from some place like cnn.com and make a php web application that spits out the headline, the story, and any photos. Make sure to strip all HTML tags.
Must use classes, constructors, and CANNOT use 3rd party libraries, native PHP is ok.
So here is the article I am working on
http://www.cnn.com/2015/11/18/us/delmarva-peninsula-squirrel-endangered-species-feat/index.html
Where I left last from frustration is this, it pulls out everything I need, but leaves the raw code showing too.
$url='http://www.cnn.com/2015/11/18/us/delmarva-peninsula-squirrel-endangered-species-feat/index.html';
$element = file_get_contents($url);
echo strip_tags($element , "<h1>, <img>, <p>");
I had this at one point as well
//Class Structure
class ThisIsMyClass {
public $aHTMLContent = 'HTMLContent';
public $aHeader = 'Header';
public $aPictures = 'Pictures';
}
$ThisIsMyClass = new ThisIsMyClass;
//Title For Page
$element = 'Header'
$ThisIsMyClass->$element=file_get_contents("http://www.cnn.com/tech", 20);
preg_match("/<title>(.*)</title>/i", $html, $match);
$title = $match[1];
echo $element . '<br>';
//HTML Content
$element2 = 'HTMLContent'
$ThisIsMyClass->$element2=getHTML("http://www.cnn.com/tech");
echo $element2 . '<br>';
//Get all images from page
$element3 = 'Pictures';
foreach($element2->find"img" as $element3)
echo $element3->src . '<br>';
?>
I see a ton of "use curl" but since curl is 3rd party I cannot use it. I have seen pulling the title specific, but the actual title is in a meta tag. I followed a couple examples on here for extracting meta tags, but I get errors that apparently no other post gets.
Please help! I need to finish this tonight, I have done my due diligence on it and I just do not know where else to look.
Ok...so I've spent the last two hours trying to look at how to add a class and constructor to this where it makes sense....
Every example I can find is the stereotypical
class human
{
function talk{
echo "Hello"}
}
etc....I am having trouble seeing how this relates to what I have going on. I am basically going off of the code structure that Chris85 posted below. I do not see how the info from the code below involves classes and a constructor....can someone help with some hints, examples, or a good tutorial that involves something a little closer to what I am working with??
Here's a rough example using the DOM parser to output all h1, img, and p elements content.
$url='http://www.cnn.com/2015/11/18/us/delmarva-peninsula-squirrel-endangered-species-feat/index.html';
$string = file_get_contents($url);
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($string);
libxml_use_internal_errors(false);
output_these_elements(array('h1', 'img', 'p'), $doc);
function output_these_elements($elements, $doc) {
foreach($elements as $element) {
echo $element . "\n\n";
$domelements = $doc->getElementsByTagName($element);
foreach($domelements as $domelement) {
if($element == 'img') {
echo $domelement->getAttribute('src') . "\n";
} else {
echo $domelement->nodeValue . "\n";
}
}
}
}
Output:
h1
Nuts to you! Squirrel gets off endangered species list
img
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110249-01-animals-endangered-species-super-169.jpg
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110527-02-animals-endangered-species-restricted-super-169.jpg
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110554-03-animals-endangered-species-super-169.jpg
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110627-04-animals-endangered-species-super-169.jpg
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110842-05-animals-endangered-species-super-169.jpg
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110903-06-animals-endangered-species-super-169.jpg
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110938-07-animals-endangered-species-super-169.jpg
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
http://i2.cdn.turner.com/cnnnext/dam/assets/151118111005-08-animals-endangered-species-super-169.jpg
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
http://i2.cdn.turner.com/cnnnext/dam/assets/151118111029-09-animals-endangered-species-super-169.jpg
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
http://i2.cdn.turner.com/cnnnext/dam/assets/151118111059-10-animals-endangered-species-super-169.jpg
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
http://i2.cdn.turner.com/cnnnext/dam/assets/151118111206-11-animals-endangered-species-super-169.jpg
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
http://i2.cdn.turner.com/cnnnext/dam/assets/151118111225-12-animals-endangered-species-super-169.jpg
data:image/gif;base64,R0lGODlhEAAJAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAQAAkAAAIKlI+py+0Po5yUFQA7
http://i2.cdn.turner.com/cnnnext/dam/assets/151118111242-13-animals-endangered-species-super-169.jpg
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110249-01-animals-endangered-species-small-11.jpg
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110527-02-animals-endangered-species-restricted-small-11.jpg
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110554-03-animals-endangered-species-small-11.jpg
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110627-04-animals-endangered-species-small-11.jpg
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110842-05-animals-endangered-species-small-11.jpg
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110903-06-animals-endangered-species-small-11.jpg
http://i2.cdn.turner.com/cnnnext/dam/assets/151118110938-07-animals-endangered-species-small-11.jpg
http://i2.cdn.turner.com/cnnnext/dam/assets/151118111005-08-animals-endangered-species-small-11.jpg
http://i2.cdn.turner.com/cnnnext/dam/assets/151118111029-09-animals-endangered-species-small-11.jpg
http://i2.cdn.turner.com/cnnnext/dam/assets/151118111059-10-animals-endangered-species-small-11.jpg
http://i2.cdn.turner.com/cnnnext/dam/assets/151118111206-11-animals-endangered-species-small-11.jpg
http://i2.cdn.turner.com/cnnnext/dam/assets/151118111225-12-animals-endangered-species-small-11.jpg
http://i2.cdn.turner.com/cnnnext/dam/assets/151118111242-13-animals-endangered-species-small-11.jpg
p
By Todd Leopold, CNN
Updated 3:54 PM ET, Wed November 18, 2015
(CNN)Forget about gathering nuts. A rare species of squirrel has gathered new life.
The Delmarva Peninsula fox squirrel, one of the animals on the original endangered species list, is now no longer at risk of extinction, says the U.S. Department of the Interior.
"The fox squirrel's return to this area, rich with farmland and forest, marks not only a major win for conservationists and landowners, but also represents the latest in a string of success stories that demonstrate the Endangered Species Act's effectiveness," Interior official Michael Bean said from Prime Hook National Wildlife Refuge in Milton, Delaware, according to a Department of the Interior statement.
The squirrel -- native to Delaware and coastal Maryland and Virginia (DelMarVa, get it?) -- will be officially removed from the list in December.
The Delmarva Peninsula fox squirrel was one of 78 species listed under the Endangered Species Preservation Act in 1967, the first year the list appeared. It continued on the successor list of Threatened and Endangered Wildlife under the Endangered Species Act, passed in 1973.
It's one of 30 species to have been delisted, according to the Interior Department. Others include the peregrine falcon, the American alligator and the national bird of the United States, the bald eagle.
Not all species make it, despite being listed. The Santa Barbara song sparrow was noted as extinct in 1983 despite 10 years on the list. Also considered extinct are the longjaw cisco, a fish once found in the Great Lakes; the Mariana mallard, a duck native to the Mariana Islands; and the Caribbean monk seal, a once-common Gulf of Mexico seal -- Columbus recorded their existence in 1494 -- that was delisted in 2008 after an exhaustive search.
The Delmarva Peninsula fox squirrel also had a difficult climb back to its current population. Larger than your average suburban nut-hoarder, it was widely found in the rural areas of the Delmarva Peninsula, a landmass between the Chesapeake Bay and the Atlantic Ocean.
But decades of development and overhunting, starting in the 1950s, limited the fox squirrel's habitat and threatened its existence.
However, "since listing, the squirrel's range has increased from four to 10 counties, and a population of up to 20,000 squirrels now covers 28 percent of the Delmarva Peninsula, primarily in Maryland," the Interior Department's statement observed. (No word on whether Atlanta's Inman Park Squirrel Census contributed to the counting.)
Still, just because the squirrel is no longer endangered, don't expect to head out immediately and start grabbing a few for dinner. According to a fact sheet, "Deliberate killing of any animal is permissible only during an open hunting season defined under state law in Maryland, Delaware and Virginia." Those states haven't decided on any details.
Not bad, Delmarva Peninsula fox squirrel. You're out of the woods -- that is, if you wanted to leave.

JSON KEY/VALUE to PHP variable

I'll get right to the point.
I'm trying to save data retrieved from an API using the following:
$i=0;
foreach($results->results as $product){
$products[$i]['pid'] = $product->listing_id;
$products[$i]['title'] = $product->title;
$products[$i]['url'] = $product->url;
$products[$i]['price'] = $product->price;
$products[$i]['quantity'] = $product->quantity;
$products[$i]['endtime'] = $product->ending_tsz;
$products[$i]['thumb'] = $product->results.Images[url_75x75];
Here is the JSON request:
{
"count":163,
"results":[
{
"listing_id":118973432,
"state":"active",
"user_id":27549667,
"category_id":68894752,
"title":"Funny I Love You Valentines Card - I Heart you Even More then a Nerd Loves Starwars - Adult Funny Humor Greeting Cards",
"description":"You know how much Nerds be loving the Star Wars , this Valentines day show the one you love that you love them even more then that - The perfect greeting card for that special someone!\r\n\r\nGUARANTEED CHRISTMAS DELIVERY - Place your orders by 12\/19 and get it by Christmas Eve - Upgraded Two Shipping available starting at $5, just contact us to upgrade\r\n\r\nDetails:\r\n\r\n- Outside Message: I love you even more then a nerd loves Starwars\r\n- Inside Message: Blank Inside\r\n- Size A7 (5x7)\r\n- Matching White Envelope included \r\n- Packaged in a cello sleeve for protection in transit\r\n\r\nWe will gladly ship to your recipient! Just specify a ship to address and any special message in "notes to seller" at checkout. Need a Custom Card, Magnet or keychain, we do that too!\r\n\r\nShipping:\r\nUS S&H is $2-Ships within 1 business day. Please allow 2-5 business days for delivery.\r\nIntl S&H is $4 - Ships within 1 business day - Please allow 7-10 business days for delivery.\r\n\r\nBuy MORE and SAVE on shipping! Express shipment is available to most US cities contact us for price and details.\r\n\r\nFor More Rude, crude and downright funny greeting cards, novelty gifts and prints, visit our Etsy store and browse a large selection single cards, greeting card sets, prints and more totally edgy, racy, adult, crass, lude, perverted and all things nasty!\r\nimjustsayininc.etsy.com",
"creation_tsz":1422565585,
"ending_tsz":1432929985,
"original_creation_tsz":1356746393,
"last_modified_tsz":1422565585,
"price":"4.00",
"currency_code":"USD",
"quantity":3,
"tags":[
"funny card",
"greeting card",
"novelty card",
"mature card",
"adult card",
"cards",
"funny cards",
"relationship card",
"love card",
"i love you card",
"valentines cards",
"funny valentine",
"valentines day card"
],
"category_path":[
"Paper Goods",
"Cards",
"Valentine"
],
"category_path_ids":[
69150367,
69152963,
68894752
],
"materials":[
"Papaer",
"Ink",
"Envelope"
],
"shop_section_id":12656719,
"featured_rank":null,
"state_tsz":1421921498,
"url":"https:\/\/www.etsy.com\/listing\/118973432\/funny-i-love-you-valentines-card-i-heart?utm_source=massetsy&utm_medium=api&utm_campaign=api",
"views":764,
"num_favorers":102,
"shipping_template_id":null,
"processing_min":1,
"processing_max":1,
"who_made":"i_did",
"is_supply":"false",
"when_made":"2010_2015",
"is_private":false,
"recipient":"unisex_adults",
"occasion":"valentines",
"style":null,
"non_taxable":false,
"is_customizable":true,
"is_digital":false,
"file_data":"",
"language":"en-US",
"has_variations":false,
"used_manufacturer":false,
"Images":[
{
"listing_image_id":410447372,
"hex_code":"C1AFB1",
"red":193,
"green":175,
"blue":177,
"hue":353,
"saturation":9,
"brightness":75,
"is_black_and_white":false,
"creation_tsz":1356746394,
"listing_id":118973432,
"rank":1,
"url_75x75":"https:\/\/img0.etsystatic.com\/015\/0\/7566894\/il_75x75.410447372_sjo4.jpg",
"url_170x135":"https:\/\/img0.etsystatic.com\/015\/0\/7566894\/il_170x135.410447372_sjo4.jpg",
"url_570xN":"https:\/\/img0.etsystatic.com\/015\/0\/7566894\/il_570xN.410447372_sjo4.jpg",
"url_fullxfull":"https:\/\/img0.etsystatic.com\/015\/0\/7566894\/il_fullxfull.410447372_sjo4.jpg",
"full_height":737,
"full_width":600
},
{
"listing_image_id":402927400,
"hex_code":"897761",
"red":137,
"green":119,
"blue":97,
"hue":33,
"saturation":29,
"brightness":53,
"is_black_and_white":false,
"creation_tsz":1356746394,
"listing_id":118973432,
"rank":2,
"url_75x75":"https:\/\/img0.etsystatic.com\/003\/0\/7566894\/il_75x75.402927400_e80x.jpg",
"url_170x135":"https:\/\/img0.etsystatic.com\/003\/0\/7566894\/il_170x135.402927400_e80x.jpg",
"url_570xN":"https:\/\/img0.etsystatic.com\/003\/0\/7566894\/il_570xN.402927400_e80x.jpg",
"url_fullxfull":"https:\/\/img0.etsystatic.com\/003\/0\/7566894\/il_fullxfull.402927400_e80x.jpg",
"full_height":800,
"full_width":986
},
{
"listing_image_id":402923983,
"hex_code":"C8C1C0",
"red":200,
"green":193,
"blue":192,
"hue":8,
"saturation":4,
"brightness":78,
"is_black_and_white":false,
"creation_tsz":1356746394,
"listing_id":118973432,
"rank":3,
"url_75x75":"https:\/\/img1.etsystatic.com\/005\/0\/7566894\/il_75x75.402923983_snri.jpg",
"url_170x135":"https:\/\/img1.etsystatic.com\/005\/0\/7566894\/il_170x135.402923983_snri.jpg",
"url_570xN":"https:\/\/img1.etsystatic.com\/005\/0\/7566894\/il_570xN.402923983_snri.jpg",
"url_fullxfull":"https:\/\/img1.etsystatic.com\/005\/0\/7566894\/il_fullxfull.402923983_snri.jpg",
"full_height":440,
"full_width":640
}
]
}
],
"params":{
"limit":"1",
"offset":0,
"page":null,
"shop_id":"imjustsayininc",
"keywords":null,
"sort_on":"created",
"sort_order":"down",
"min_price":null,
"max_price":null,
"color":null,
"color_accuracy":0,
"tags":null,
"category":null,
"translate_keywords":"false",
"include_private":0
},
"type":"Listing",
"pagination":{
"effective_limit":1,
"effective_offset":0,
"next_offset":1,
"effective_page":1,
"next_page":2
}
}
What I'm trying to do is pull all values from the image field where it shows an image URL (url_75x75,url_170x135,url_570xN & url_fullxfull).
I seem to be stuck only on the importing of the images. They seems to be in an array and I can't figure out how to implement pulling them like I do the rest of the content.
I've spent roughly 3 days searching, trying and failing at doing this.
I was successful when I had the Json request split up into separate requests but recently learned I could include images into one JSON request which is the method I am currently trying.
How can I do this?
I'm pretty new to PHP and I'm even newer at JSON so please be descriptive as possible and try not to overload me with complex ways I could do this, thank you.
results is an array of objects, so is Images
I didn't test it but I think something like this should be able to retrieve the first image of the first result:
$product->results[0]->Images[0]->url_75x75
In your code, this is obviously wrong:
$product->results.Images[url_75x75]
Javascript with PHP syntax mixed together? ;-)

How to implement pushState() and popState() with ajaxed content in JSON format?

Short Version
What content does the content.php file referenced in this tutorial have?
http://moz.com/blog/create-crawlable-link-friendly-ajax-websites-using-pushstate
Long Version With Research
The tutorial above is the most succinct I have come across for implementing pushState() and popState() in a scenario where you are loading content via Ajax but want to retain bookmarking and browser backwards and forwards navigation functionality:
A demo page has been set up as a proof of concept:
http://html5.gingerhost.com/
Where the source code is as below.
There are several in-between steps needed to implement it however that I'm not totally familiar with:
Setting up a PHP file of content in JSON format
Understanding JSON formatting
A comment on this post html5 pushstate example and jquery's $.getJSON suggests using Firebug to see the HTTP request response in order to see the JSON formatting.
With Firebug loaded, and Console > All selected, when I click on the navigation links I see entries like:
GET http://html5.gingerhost.com/content.php?cid=%2F&format=json 200 OK 869ms
GET http://html5.gingerhost.com/content.php?cid=%2Fseattle&format=json 200 OK 859ms
GET http://html5.gingerhost.com/content.php?cid=%2Fnew-york&format=json 200 OK 837ms
GET http://html5.gingerhost.com/content.php?cid=%2Flondon&format=json 200 OK 863ms
The corresponding content from the 'Reponse' tab for each entry is in the JSON format:
{"title":"Title value here","h1":"H1 value here","article #articletext":"<p>Lots of html here.<\/p><p>That includes escaped characters.<\/p>","#image":"<img class=\"thumbnail\" alt=\"\" src=\"and_an_image.jpg\">"}
So after some research, JSON format seems to be:
{
"myArrayName": [
{ "Key1":"Value1" , "Key2":"Value2" }, // object one
{ "Key1":"Value3" , "Key2":"Value4" }, // object two
{ "Key1":"Value5" , "Key2":"Value6" }, // object three
]
}
Adding a 'real world' example to that would make it:
{
"myCDCollection": [
{ "Title":"Trash" , "Artist":"Alice Cooper" }, // object one
{ "Title":"Dr. Feelgood" , "Artist":"Motley Crue" }, // object two
{ "Title":"Cherry Pie" , "Artist":"Warrant" }, // object three
]
}
So the keys in the proof of concept seem to be:
title
h1
article #articletext
#image
So my question is what content does the content.php file referenced in the tutorial need to have?
Is it just a matter of copying and pasting the JSON objects, separated by commas?
Do they need to be encapsulated in an array?
Does the array need a name?
Which is then encapsulated in curly braces?
Does the PHP file need a MIME media type specified, if so where and how?
Here is the script from the proof of concept:
<script>
// THIS IS WHERE THE MAGIC HAPPENS
$(function() {
$('nav a').click(function(e) {
$("#loading").show();
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.getJSON("content.php", {cid: url, format: 'json'}, function(json) {
// THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES
$.each(json, function(key, value){
$(key).html(value);
});
$("#loading").hide();
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
</script>
It doesn't matter what content.php contains, it is just supposed to return some content that is then manipulated by javascript and loaded into the DOM. You can't really determine what his content.php contains, but given the limited scope of the page, here is one possibility:
<?php
$page = $_GET['cid'];
$pageData = array();
switch ($page) {
case '/':
$pageData = array(
'title' => 'Seattle - Part of a demo for #ProSEO',
'h1' => 'Seattle',
'article #articletext' => '<p>Seattle is the northernmost major city in the contiguous United States, and the largest city in the Pacific Northwest and the state of Washington. It is a major seaport situated on a narrow isthmus between Puget Sound (an arm of the Pacific Ocean) and Lake Washington, about 114 miles (183 km) south of the Canada - United States border, and it is named after Chief Sealth \"Seattle\", of the Duwamish and Suquamish native tribes. Seattle is the center of the Seattle-Tacoma-Bellevue metropolitan statistical area--the 15th largest metropolitan area in the United States, and the largest in the northwestern United States.<\/p><p>Seattle is the county seat of King County and is the major economic, cultural and educational center in the region. The 2010 census found that Seattle is home to 608,660 residents within a metropolitan area of some 3.4 million inhabitants. The Port of Seattle, which also operates Seattle-Tacoma International Airport, is a major gateway for trade with Asia and cruises to Alaska, and is the 8th largest port in the United States in terms of container capacity.<\/p>',
'#image' => '<img class=\"thumbnail\" alt=\"\" src=\"seattle.jpg\">'
);
break;
case '/new-york':
$pageData = array(
'title' => 'New York - Part of a demo for #ProSEO',
'h1' => 'New York',
'article #articletext' => '<p>New York is the most populous city in the United States and the center of the New York metropolitan area, which is one of the most populous metropolitan areas in the world. New York City exerts a significant impact upon global commerce, finance, media, culture, art, fashion, research, technology, education, and entertainment. As the home of the United Nations Headquarters, it is also an important center for international affairs. The city is often referred to as New York City or the City of New York, to distinguish it from the state of New York, of which it is a part.<\/p>',
'#image' => '<img class=\"thumbnail\" alt=\"\" src=\"new-york.jpg\">'
);
break;
case '/london':
// similar code for london
break;
case '/seattle':
// similar code for seattle
break;
}
header('Content-Type: application/json');
echo json_encode($pageData);
?>
In reality it most likely retrieves the page data from an external source like a database.
Is it just a matter of copying and pasting the JSON objects, separated by commas?
Do they need to be encapsulated in an array?
Nothing needs to be encapsulated in an array - it doesn't matter how it gets there (you could generate the JSON yourself manuallly) as long as that's what the output is (a json-valid file). And you specify the MIMEtype of the response to application/json using the header method in PHP.

XML to PHP array, and HTML Tags

Hi there i have got my feed functioning problem I have is in the xml there is description tag and inside is html code. now php is treating the HTML tags as other xml tags and making more arrays. How can I stop this from creating arrays out of the HTML tags?
eg.
<description>
<h3>Some text</h3>
</description>
its out putting
array['description'] => array['h3'] => "someText"
PHP code:
public function merchant_import_wahanda(){
if (!$this->session->userdata('logged_in')){
redirect('admin/login');
}
$data['pageTitle'] = 'Merchant Admin';
$data['error_warning'] = '';
$data['success'] = '';
$xmlfile= 'http://www.wahanda.com/rss/mobdeal.xml';
$xmlRaw = file_get_contents($xmlfile);
$this->load->library('xml');
$xmlData = $this->xml->xml_parse($xmlRaw);
$this->load->model('admin/Deals_model', 'Deals');
$this->load->model('admin/Cities_model', 'Cities');
$this->load->model('admin/Partners_model', 'Partners');
//Get City ID
foreach($xmlData["channel"]["item"] as $product){
$cityName[] = $product['w:location']["#content"];
}
$cities = array_unique($cityName);
foreach ($cities as $city){
if(!$this->Cities->getCityByName($city)){
$this->Cities->addFeedCity($city);
}
}
//Get Partner ID
foreach($xmlData["channel"]["item"] as $product){
$partnerName[] = $product['w:venues']['w:venue']['w:name'];
}
$partners = array_unique($partnerName);
foreach ($partners as $partner){
if(!$this->Partners->getPartnerByName($partner)){
$this->Partners->addFeedPartner($partner);
}
}
foreach($xmlData["channel"]["item"] as $product){
$cityID = $this->Cities->getCityByName($product['w:location']["#content"]);
$partnerID = $this->Partners->getPartnerByName($product['w:venues']['w:venue']['w:name']);
$deals[] = array(
'dealTitle' => $product['title'],
'price' => $product['w:price'],
'image' => $product['w:hiResImageLink'],
'buyLink' => $product['link'],
'startDate' => $product['w:startDate'],
'endDate' => $product['w:endDate'],
'partner' => $partnerID['partner_id'],
'city' => $cityID['city_id'],
'description' => $product['description'],
'RRP' => $product['w:rrp'],
'discount' => $this->getDiscount($product['w:price'], $product['w:rrp'])
);
}
?><pre><?php var_dump($deals); ?></pre><?php
foreach($deals as $deal){
$this->Deals->importWahanda($deal);
}
}
XML Description example:
<description>
<a id="Wahanda_loves" name="Wahanda_loves"></a><h3>Wahanda loves</h3>
<p>If you're fed up of shaving and can't bear the pain of waxing then remove hair the easy way with this course of IPL hair removal. It works by using beams of light to damage the hair follicle, meaning after a course of treatment you'll be hair-free for longer. Five sessions will catch the hair in each stage of the growth cycle so your skin will stay silky-smooth and fuzz-free for longer.</p>
<a id="What.27s_in_it_for_you.3F" name="What.27s_in_it_for_you.3F"></a><h3>What's in it for you?</h3>
<ul>
<li>Five IPL Sessions on <b>one</b> of the following areas:
<ul>
<li>Lip and Chin</li>
<li>Bikini Line</li>
<li>Underarm</li></ul></li></ul>
<ul>
<li>Location: DepiCool, Leeds</li>
<li>Available Monday - Saturday</li>
<li><b>Strict voucher limit of 1 per person.</b> May buy multiples as gifts</li>
<li>You will receive an eVoucher valid for one person to print out and take with you.</li>
<li>Voucher valid for 6 months</li>
<li>Cannot be used in conjunction with any other offer. Subject to availability. No cash alternative</li></ul>
<p>You'll get a snazzy pair of goggles to wear during the treatment so your eyes are protected throughout the fifteen minute procedure. DepiCool's therapists are fully qualified and consider your comfort and safety to be the most important part of the treatment process. All staff are trained to be able to answer your questions so you'll be informed at at ease at all times. </p>
<a id="Want_to_buy_this_as_a_gift.3F" name="Want_to_buy_this_as_a_gift.3F"></a><h3>Want to buy this as a gift?</h3>
<p>If you're feeling generous and want to buy this as a gift for someone, don't worry - the voucher won't show the price or discount of the MobDeal if you add a gift message, making it perfect for giving as a gift. All you need to do is choose how many vouchers you'd like to buy at checkout so you can enter each recipient's name on the coupon, then add your message for the lucky recipient.</p></description>
You can either place your HTML into CDATA, as suggested by Agop, or encode the characters - use < instead of <, > instead of >, etc. As far as XML is concerned, they are identical. I'd go for the CDATA option since you have many lines of HTML, and it's more readable.
<description>
<![CDATA[<a id="Wahanda_loves" name="Wahanda_loves"></a><h3>Wahanda loves</h3>
<p>If you're fed up of shaving and can't bear the pain of waxing then remove hair the easy way with this course of IPL hair removal. It works by using beams of light to damage the hair follicle, meaning after a course of treatment you'll be hair-free for longer. Five sessions will catch the hair in each stage of the growth cycle so your skin will stay silky-smooth and fuzz-free for longer.</p>
<a id="What.27s_in_it_for_you.3F" name="What.27s_in_it_for_you.3F"></a><h3>What's in it for you?</h3>
...
]]>
</description>
CDATA ?

Categories