So the new Google custom Search has rolled out and im having trouble displaying the results...
I am using php to return the results in json and am getting a invalid argument in for each error... Here is what i am using...
$url = "https://www.googleapis.com/customsearch/v1?key=MYKEY&cx=017576662512468239146:omuauf_lfve&q=test&callback=json";
$results = file_get_contents($url);
foreach ($results->items as $r)
{
}
Here's the callback when I go to the URL in the browser:
json({
"kind": "customsearch#search",
"url": {
"type": "application/json",
"template": "https://www.googleapis.com/customsearch/v1?q\u003d{searchTerms}&num\u003d{count?}&start\u003d{startIndex?}&hr\u003d{language?}&safe\u003d{safe?}&cx\u003d{cx?}&cref\u003d{cref?}&sort\u003d{sort?}&alt\u003djson"
},
"queries": {
"nextPage": [
{
"title": "Google Custom Search - test",
"totalResults": 276000000,
"searchTerms": "test",
"count": 10,
"startIndex": 11,
"inputEncoding": "utf8",
"outputEncoding": "utf8",
"safe": "off",
"cx": "017576662512468239146:omuauf_lfve"
}
],
"request": [
{
"title": "Google Custom Search - test",
"totalResults": 276000000,
"searchTerms": "test",
"count": 10,
"startIndex": 1,
"inputEncoding": "utf8",
"outputEncoding": "utf8",
"safe": "off",
"cx": "017576662512468239146:omuauf_lfve"
}
]
},
"context": {
"title": "Curriculum",
"facets": [
[
{
"label": "lectures",
"anchor": "Lectures"
}
],
[
{
"label": "assignments",
"anchor": "Assignments"
}
],
[
{
"label": "reference",
"anchor": "Reference"
}
]
]
},
"items": [
{
"kind": "customsearch#result",
"title": "Lecture 8: Pseudo Randomness and the Next-bit test 1 Review 2 ...",
"htmlTitle": "Lecture 8: Pseudo Randomness and the Next-bit \u003cb\u003etest\u003c/b\u003e 1 Review 2 \u003cb\u003e...\u003c/b\u003e",
"link": "http://www.cs.cornell.edu/courses/cs687/2008sp/scribes/scribe19Feb2008.pdf",
"displayLink": "www.cs.cornell.edu",
"snippet": "Feb 19, 2008 ... Definition 2 An ensemble {Xn} passes the Next Bit test ⇐⇒ ∀ PPT A, ... Next Bit test. We have to now prove the other direction. ...",
"htmlSnippet": "Feb 19, 2008 \u003cb\u003e...\u003c/b\u003e Definition 2 An ensemble {Xn} passes the Next Bit \u003cb\u003etest\u003c/b\u003e ⇐⇒ ∀ PPT A, \u003cb\u003e...\u003c/b\u003e Next \u003cbr\u003e Bit \u003cb\u003etest\u003c/b\u003e. We have to now prove the other direction. \u003cb\u003e...\u003c/b\u003e",
"cacheId": "ErjWs7c3umEJ",
"pagemap": {
"metatags": [
{
"producer": "MiKTeX pdfTeX-1.40.4",
"creator": "TeX",
"creationdate": "D:20080306114145-05'00'",
"moddate": "D:20080306114145-05'00'",
"fullbanner": "This is MiKTeX-pdfTeX 2.7.2808 (1.40.4)"
}
]
}
},
{
"kind": "customsearch#result",
"title": "General Information for Computer Science 227 and 228 Test-Out ...",
"htmlTitle": "General Information for Computer Science 227 and 228 \u003cb\u003eTest\u003c/b\u003e-Out \u003cb\u003e...\u003c/b\u003e",
"link": "http://www.cs.iastate.edu/gradadm/cmarquar/testout.pdf",
"displayLink": "www.cs.iastate.edu",
"snippet": "should fill out an application for a test-out in the main office and find ... \" Students may ordinarily attempt a CBE test only once in any course or area. ...",
"htmlSnippet": "should fill out an application for a \u003cb\u003etest\u003c/b\u003e-out in the main office and find \u003cb\u003e...\u003c/b\u003e "\u003cbr\u003e Students may ordinarily attempt a CBE \u003cb\u003etest\u003c/b\u003e only once in any course or area. \u003cb\u003e...\u003c/b\u003e",
"cacheId": "HvE3JGhnVkgJ",
"pagemap": {
"metatags": [
{
"creationdate": "D:20091006145719-05'00'",
"author": "prabhu",
"creator": "PScript5.dll Version 5.2.2",
"producer": "Acrobat Distiller 7.0 (Windows)",
"moddate": "D:20091006145719-05'00'"
}
]
}
},
{
"kind": "customsearch#result",
"title": "CS1130 Grades/exams/assignments",
"htmlTitle": "CS1130 Grades/exams/assignments",
"link": "http://www.cs.cornell.edu/courses/cs1130/2010fa/gradesexams.html",
"displayLink": "www.cs.cornell.edu",
"snippet": "There will be two tests. The exams require mastery of the material: you will be expected to get 85% on each test. If you get lower than 85% on a test, ...",
"htmlSnippet": "There will be two \u003cb\u003etests\u003c/b\u003e. The exams require mastery of the material: you will be \u003cbr\u003e expected to get 85% on each \u003cb\u003etest\u003c/b\u003e. If you get lower than 85% on a \u003cb\u003etest\u003c/b\u003e, \u003cb\u003e...\u003c/b\u003e",
"cacheId": "fjSAJnTr0FgJ"
},
{
"kind": "customsearch#result",
"title": "Lecture 16: Recognition II Outline Model-based recognition ...",
"htmlTitle": "Lecture 16: Recognition II Outline Model-based recognition \u003cb\u003e...\u003c/b\u003e",
"link": "http://www.cs.utexas.edu/~grauman/courses/378/slides/lecture16.pdf",
"displayLink": "www.cs.utexas.edu",
"snippet": "Hypothesize and test. • Given model of object .... Hypothesize and test: looking for object and ... “Test” as function of these representations that ...",
"htmlSnippet": "Hypothesize and \u003cb\u003etest\u003c/b\u003e. • Given model of object \u003cb\u003e....\u003c/b\u003e Hypothesize and \u003cb\u003etest\u003c/b\u003e: looking \u003cbr\u003e for object and \u003cb\u003e...\u003c/b\u003e “\u003cb\u003eTest\u003c/b\u003e” as function of these representations that \u003cb\u003e...\u003c/b\u003e",
"cacheId": "_QUgy1DsMFgJ",
"pagemap": {
"metatags": [
{
"creationdate": "D:20071108175221-06'00'",
"author": "grauman",
"creator": "PScript5.dll Version 5.2.2",
"producer": "Acrobat Distiller 8.1.0 (Windows)",
"moddate": "D:20071108175221-06'00'"
}
]
}
},
{
"kind": "customsearch#result",
"title": "Notes on the Miller-Rabin randomized primality test",
"htmlTitle": "Notes on the Miller-Rabin randomized primality \u003cb\u003etest\u003c/b\u003e",
"link": "http://www.cs.cornell.edu/courses/cs482/2008sp/handouts/mrpt.pdf",
"displayLink": "www.cs.cornell.edu",
"snippet": "Apr 25, 2008 ... test whether a number is prime. It is called the Miller-Rabin primality .... The Miller-Rabin test is based on a third way to prove that a ...",
"htmlSnippet": "Apr 25, 2008 \u003cb\u003e...\u003c/b\u003e \u003cb\u003etest\u003c/b\u003e whether a number is prime. It is called the Miller-Rabin primality \u003cb\u003e....\u003c/b\u003e The \u003cbr\u003e Miller-Rabin \u003cb\u003etest\u003c/b\u003e is based on a third way to prove that a \u003cb\u003e...\u003c/b\u003e",
"cacheId": "IP9TrtclTpAJ",
"pagemap": {
"metatags": [
{
"producer": "pdfTeX-1.40.3",
"creator": "TeX",
"creationdate": "D:20080424173852-04'00'",
"moddate": "D:20080424173852-04'00'",
"fullbanner": "This is pdfTeX, Version 3.141592-1.40.3-2.2 (Web2C 7.5.6) kpathsea version 3.5.6"
}
]
}
},
{
"kind": "customsearch#result",
"title": "TOWARD A THEORY OF TEST DATA SELECTION John B. Go0denough Susan L ...",
"htmlTitle": "TOWARD A THEORY OF \u003cb\u003eTEST\u003c/b\u003e DATA SELECTION John B. Go0denough Susan L \u003cb\u003e...\u003c/b\u003e",
"link": "http://www.cs.umd.edu/class/spring2003/cmsc838p/VandV/criteria.pdf",
"displayLink": "www.cs.umd.edu",
"snippet": "Formal Definitions and the Fundamental Theorem of Testing criterion is reliable if and only if ... set of test data, i. e. , if it can be shown that for ...",
"htmlSnippet": "Formal Definitions and the Fundamental Theorem of \u003cb\u003eTesting\u003c/b\u003e criterion is reliable \u003cbr\u003e if and only if \u003cb\u003e...\u003c/b\u003e set of \u003cb\u003etest\u003c/b\u003e data, i. e. , if it can be shown that for \u003cb\u003e...\u003c/b\u003e",
"cacheId": "44B1_Z8kNHYJ",
"pagemap": {
"metatags": [
{
"moddate": "D:20010115130600-05'00'",
"creationdate": "D:20010114103427-05'00'"
}
]
}
},
{
"kind": "customsearch#result",
"title": "Lecture Notes 16 - pmwiki - Main.homepage",
"htmlTitle": "Lecture Notes 16 - pmwiki - Main.homepage",
"link": "http://zoo.cs.yale.edu/classes/cs467/2008f/attach/ln16.html",
"displayLink": "zoo.cs.yale.edu",
"snippet": "Nov 3, 2008 ... If n is prime, the test always fails by Theorem 1 of section 68. ... The test μa (n) is based on computing a sequence b0,b1,…,bs of integers ...",
"htmlSnippet": "Nov 3, 2008 \u003cb\u003e...\u003c/b\u003e If n is prime, the \u003cb\u003etest\u003c/b\u003e always fails by Theorem 1 of section 68. \u003cb\u003e...\u003c/b\u003e The \u003cb\u003etest\u003c/b\u003e μa\u003cbr\u003e (n) is based on computing a sequence b0,b1,…,bs of integers \u003cb\u003e...\u003c/b\u003e",
"cacheId": "TnMAQxlY3HIJ",
"pagemap": {
"metatags": [
{
"originator": "TeX4ht (http://www.cse.ohio-state.edu/~gurari/TeX4ht/)",
"src": "ln16.tex",
"date": "2008-11-11 16:55:00"
}
]
}
},
{
"kind": "customsearch#result",
"title": "CS 337 Test 3 5/5/06 Open book and notes. Max points \u003d 50 Time ...",
"htmlTitle": "CS 337 \u003cb\u003eTest\u003c/b\u003e 3 5/5/06 Open book and notes. Max points \u003d 50 Time \u003cb\u003e...\u003c/b\u003e",
"link": "http://www.cs.utexas.edu/users/misra/Classes.dir/337quizSoln.dir/S06.quiz3.pdf",
"displayLink": "www.cs.utexas.edu",
"snippet": "Test 3. 5/5/06. Open book and notes. Max points \u003d 50. Time \u003d 50 min. Do all questions. 1. (Relational Algebra; 15 points) ...",
"htmlSnippet": "\u003cb\u003eTest\u003c/b\u003e 3. 5/5/06. Open book and notes. Max points \u003d 50. Time \u003d 50 min. Do all \u003cbr\u003e questions. 1. (Relational Algebra; 15 points) \u003cb\u003e...\u003c/b\u003e",
"cacheId": "ClTLaytSRUIJ",
"pagemap": {
"metatags": [
{
"creator": "TeX output 2006.05.04:1646",
"producer": "dvipdfm 0.13.2c, Copyright Š 1998, by Mark A. Wicks",
"creationdate": "D:20060504164645-06'00'"
}
]
}
},
{
"kind": "customsearch#result",
"title": "EE410 Test Structures & Testing",
"htmlTitle": "EE410 \u003cb\u003eTest\u003c/b\u003e Structures & \u003cb\u003eTesting\u003c/b\u003e",
"link": "http://www.stanford.edu/class/ee410/TestStructures.pdf",
"displayLink": "www.stanford.edu",
"snippet": "Test every unique structure at least once, but don't waste time testing ..... Take good care of the testing setup — it's your only one and it cannot ...",
"htmlSnippet": "\u003cb\u003eTest\u003c/b\u003e every unique structure at least once, but don't waste time \u003cb\u003etesting\u003c/b\u003e \u003cb\u003e.....\u003c/b\u003e \u003cbr\u003e Take good care of the \u003cb\u003etesting\u003c/b\u003e setup — it's your only one and it cannot \u003cb\u003e...\u003c/b\u003e",
"cacheId": "YKadfqMlYuIJ",
"pagemap": {
"metatags": [
{
"author": "Krishna Saraswat",
"producer": "Mac OS X 10.6.6 Quartz PDFContext",
"creator": "Microsoft PowerPoint",
"creationdate": "D:20110209003235Z00'00'",
"moddate": "D:20110209003235Z00'00'"
}
]
}
},
{
"kind": "customsearch#result",
"title": "SIP: Interoperability Test Event FAQ",
"htmlTitle": "SIP: Interoperability \u003cb\u003eTest\u003c/b\u003e Event FAQ",
"link": "http://www.cs.columbia.edu/sip/sipit/faq.html",
"displayLink": "www.cs.columbia.edu",
"snippet": "\"The interoperability test event is for non-competitve, friendly testing of ... It is meant as someplace people can come to, and test their code at, ...",
"htmlSnippet": ""The interoperability \u003cb\u003etest\u003c/b\u003e event is for non-competitve, friendly \u003cb\u003etesting\u003c/b\u003e of \u003cb\u003e...\u003c/b\u003e \u003cbr\u003e It is meant as someplace people can come to, and \u003cb\u003etest\u003c/b\u003e their code at, \u003cb\u003e...\u003c/b\u003e",
"cacheId": "m7jgghXfi78J",
"pagemap": {
"metatags": [
{
"author": "Henning Schulzrinne"
}
]
}
}
]
}
);
You should try this:
$results = json_decode(file_get_contents($url));
To be able to correctly decode the response of the service, you may do the following:
$json = file_get_contents($url);
$start = 'json(';
$end = ');';
$substr_start_pos = strpos($json, $start) + strlen($start);
$substr_length = strlen($json) - $substr_start_pos - (strlen($json) - strrpos($json, $end));
$json = substr($json, $substr_start_pos, $substr_length);
$results = json_decode($json);
This may be a bit confusing, but I did this for the following reasons:
The sample response you provided, has a 'json(' string before the actual JSON, and a ');' after it, which can't be decoded with PHP's json_decode.
Simple replacing won't be good, because the actual JSON might contain these substrings as well.
THIS IS TRUE SIMPLE PHP DECODE WILL NOT HELP YOU,
TRY THIS
$data = html_entity_decode($url);
I am sure this will work properly
to try later var dump the date to check the results.
Related
I have a randquotes.json file
{
"author": "William Shakespeare",
"quotes": "A brave flea is a flea that can dare to get its breakfast on the lips of a lion."
},
{
"author": "Winston Churchill",
"quotes": "We live with what we get, but we bring life to what we give."
},
{
"author": "Wolfgang von Gothe",
"quotes": "Knowledge is not enough, we must practice it. Intention is not enough, we must do it."
}
Then I want "author" and "quotes" to be generated randomly with php
How?
thanks for help
Assuming you actually have valid a JSON string...
Convert the json to a PHP datatype using json_decode()
find out how large the array is
generate a random number between 0 and array size
Return that array occurance, I did that as a json string again using json_encode()
$json_string = '
[
{
"author": "William Shakespeare",
"quotes": "A brave flea is a flea that can dare to get its breakfast on the lips of a lion."
},
{
"author": "Winston Churchill",
"quotes": "We live with what we get, but we bring life to what we give."
},
{
"author": "Wolfgang von Gothe",
"quotes": "Knowledge is not enough, we must practice it. Intention is not enough, we must do it."
}
]';
$arr = json_decode($json_string);
// How big is the array
$max = count($arr) -1;
$rand_idx = rand(0, $max);
echo json_encode($arr[$rand_idx]);
What i want is to display all products that below to category with id 1 in.
Is displaying all products but as well looping 3 times category with each products what i want is to be .
one category with holder each and all product in each
here is my code:
$query_cat = query("SELECT * FROM categories");
$query = query("SELECT * FROM products WHERE product_category_id = '1'");
confirm($query_cat, $query);
$cat = fetch_array($query_cat);
while(($row = fetch_array($query))){
$category[] = array(
'category_id'=>$cat['cat_id'],
'category_title'=>$cat['cat_title'],
'each' => $item[] = array (
'product_id'=>$row['product_id'],
'name'=>$row['product_title'],
'product_tags'=>$row['product_category'],
'partner_name_title'=>$row['partner_name_title'],
'product_category_id'=>$row['product_category_id'],
'image'=> $produc_img,
'price'=>$row['product_price'],
'discount'=>$row['product_discount'],
'from_date'=>$row['start_discount'],
'to_date'=>$row['finish_discount'],
'sold'=>$row['counter_sold'],
'desc'=>$row['product_about'],
'location_address'=>$row['product_address'],
'location'=>$row['product_location'],
'partner_phone'=>$row['product_phone'],
'partner_email'=>$row['product_email'],
'partner_open_time'=>$row['product_open_time'],
'partner_website'=>$row['product_website'],
'instagram_page'=>$row['instagram_page'],
'facebook_page'=>$row['facebook_page'],
'product_prev'=>$row['product_prev'],
'exp'=>$row['expire']
)
);
}
}
header("Content-Type: application/json");
echo json_encode(array('pro'=>$category), JSON_PRETTY_PRINT);
OUTPUT:
{
"pro": [
{
"category_id": "1",
"category_title": "Food & Drink",
"each": {
"product_id": "84",
"name": "Night Diner",
"product_tags": "appetisers, food , health food, amazing , good .",
"partner_name_title": "Apantisi",
"product_category_id": "1",
"image": null,
"price": "1",
"discount": "-30%",
"from_date": "2020-07-25",
"to_date": "2020-12-25",
"sold": "0",
"desc": "Our restaurant proposing you to spend amazing time with you family get the taste of Caribbeans dishes \r\nOur restaurant proposing you to spend amazing time with you family get the taste of Caribbeans dishes \r\nOur restaurant proposing you to spend amazing time with you family get the taste of Caribbeans dishes ",
"location_address": "Glyfu 5 a",
"location": "Nicosia",
"partner_phone": "+357 97 832 983",
"partner_email": "apantisi#gmail.com",
"partner_open_time": "12:00-22:00",
"partner_website": "www.apantisi.com.cy",
"instagram_page": "instagram.com\/apantisi",
"facebook_page": "facebook.com\/apantisi",
"product_prev": "This coupon gives you discount -30% on any reserved table in our restaurant .",
"exp": "no"
}
},
{
"category_id": "1",
"category_title": "Food & Drink",
"each": {
"product_id": "85",
"name": "Princess Hair ",
"product_tags": "hair , extensions hair, beauty , saloon ",
"partner_name_title": "Princess Hair",
"product_category_id": "1",
"image": null,
"price": "1",
"discount": "-50%",
"from_date": "2020-07-25",
"to_date": "2020-12-25",
"sold": "2",
"desc": "is the wonderful saloon hair for you we offer you best quality of hair \r\nis the wonderful saloon hair for you we offer you best quality of hair \r\nis the wonderful saloon hair for you we offer you best quality of hair \r\nis the wonderful saloon hair for you we offer you best quality of hair ",
"location_address": " 1 Michail Georgalla Street",
"location": "Nicosia",
"partner_phone": "+357 97 832 983",
"partner_email": "hair#gmail.com",
"partner_open_time": "8:00-15:00 ",
"partner_website": "www.hair.com.cy",
"instagram_page": "instagram.com\/.hair",
"facebook_page": "instagram.com\/.hair",
"product_prev": "We offer you discount with -50% on our product bt code from coalaboom \/ use the chance to come with the code by issue date ",
"exp": "no"
}
}
but what i need is :
"pro": [
{
"category_id": "1",
"category_title": "Food & Drink",
"each": {
"product_id": "84",
"name": "Night Diner",
"product_tags": "appetisers, food , health food, amazing , good .",
"partner_name_title": "Apantisi",
"product_category_id": "1",
"image": null,
"price": "1",
"discount": "-30%",
"from_date": "2020-07-25",
"to_date": "2020-12-25",
"sold": "0",
"desc": "Our restaurant proposing you to spend amazing time with you family get the taste of Caribbeans dishes \r\nOur restaurant proposing you to spend amazing time with you family get the taste of Caribbeans dishes \r\nOur restaurant proposing you to spend amazing time with you family get the taste of Caribbeans dishes ",
"location_address": "Glyfu 5 a",
"location": "Nicosia",
"partner_phone": "+357 97 832 983",
"partner_email": "apantisi#gmail.com",
"partner_open_time": "12:00-22:00",
"partner_website": "www.apantisi.com.cy",
"instagram_page": "instagram.com\/apantisi",
"facebook_page": "facebook.com\/apantisi",
"product_prev": "This coupon gives you discount -30% on any reserved table in our restaurant .",
"exp": "no"
},
{
"product_id": "85",
"name": "Princess Hair ",
"product_tags": "hair , extensions hair, beauty , saloon ",
"partner_name_title": "Princess Hair",
"product_category_id": "1",
"image": null,
"price": "1",
"discount": "-50%",
"from_date": "2020-07-25",
"to_date": "2020-12-25",
"sold": "2",
"desc": "is the wonderful saloon hair for you we offer you best quality of hair \r\nis the wonderful saloon hair for you we offer you best quality of hair \r\nis the wonderful saloon hair for you we offer you best quality of hair \r\nis the wonderful saloon hair for you we offer you best quality of hair ",
"location_address": " 1 Michail Georgalla Street",
"location": "Nicosia",
"partner_phone": "+357 97 832 983",
"partner_email": "hair#gmail.com",
"partner_open_time": "8:00-15:00 ",
"partner_website": "www.hair.com.cy",
"instagram_page": "instagram.com\/.hair",
"facebook_page": "instagram.com\/.hair",
"product_prev": "We offer you discount with -50% on our product bt code from coalaboom \/ use the chance to come with the code by issue date ",
"exp": "no"
}
}
I want display product in each by category 1
Replace your while with:
$category = [
'category_id'=>$cat['cat_id'],
'category_title'=>$cat['cat_title'],
'each' => [],
];
while(($row = fetch_array($query))){
$category['each'][] = [
'product_id'=>$row['product_id'],
// ... rest of $row attributes
];
}
With this there will be one category and each product will have its entry in each key.
I have a JSON file that I want to use PHP to replace the "Systems_x0020_Changed_IDs" value from a string to an array. "39122" becomes [39122] and "39223, 39244, 39395" becomes [39223, 39244, 39395]. I am using http://www.regexpal.com/ to test my expression. The expression is:
"([(0-9)+((, *))]+)+"
This is producing unexpected results in PHP. In my JSON file:
[{
"ID": 1050436,
"Title": "THE SKY IS FALLING!!!!",
"Application_x0020_ID": 242,
"Systems_x0020_Changed": "Academic Planning System (APS),\"Documents planning and evaluation processes at UGA that support cont",
"Systems_x0020_Changed_IDs": "39122",
"Status": "New",
"Modified": "2015-10-28T16:14:45.573-04:00",
"Age": 40,
"Description_x0020__x0028_Public_x0029_": "I'm chicken little and the SKY IS FALLING!",
"Impact_x0020__x0028_Public_x0029_": "The world is going to end!",
"Start_x0020_Time": "2015-10-28T00:00:00-04:00",
"End_x0020_Time": "2015-10-30T00:00:00-04:00",
"Hours": 12
}, {
"ID": 1050740,
"Title": "This is a Title",
"Application_x0020_ID": 242,
"Systems_x0020_Changed": "EITS Websites,\"EITS departmental web pages.\", GACRC Archival Storage,\"Archival Storage for Research Data\", VPS,\"Mainframe distributed printing system\"",
"Systems_x0020_Changed_IDs": "39223, 39244, 39395",
"Status": "New",
"Modified": "2015-11-05T17:31:13.15-05:00",
"Age": 32,
"Description_x0020__x0028_Public_x0029_": "We will tell jokes to the clients",
"Impact_x0020__x0028_Public_x0029_": "Everyone will notice the change.",
"Start_x0020_Time": "2015-11-27T08:38:00-05:00",
"End_x0020_Time": "2015-11-30T00:00:00-05:00",
"Hours": 1
}]
Several commas at the end of lines are being replaced with brackets[] so that the output looks like:
[{
"ID": 1050436,
"Title": "THE SKY IS FALLING!!!![,]Application_x0020_ID": 242,
"Systems_x0020_Changed": "Academic Planning System (APS),\"Documents planning and evaluation processes at UGA that support cont[,]Systems_x0020_Changed_IDs": 39122,
"Status": "New[,]Modified": "2015-10-28T16:14:45.573-04:00[,]Age": 40,
"Description_x0020__x0028_Public_x0029_": "I'm chicken little and the SKY IS FALLING![,]Impact_x0020__x0028_Public_x0029_": "The world is going to end![,]Start_x0020_Time": "2015-10-28T00:00:00-04:00[,]End_x0020_Time": "2015-10-30T00:00:00-04:00[,]Hours": 12
}, {
"ID": 1050740,
"Title": "This is a Title[,]Application_x0020_ID": 242,
"Systems_x0020_Changed": "EITS Websites,\"EITS departmental web pages.\", GACRC Archival Storage,\"Archival Storage for Research Data\", VPS,\"Mainframe distributed printing system\"[,]Systems_x0020_Changed_IDs": [39223, 39244, 39395],
"Status": "New[,]Modified": "2015-11-05T17:31:13.15-05:00[,]Age": 32,
"Description_x0020__x0028_Public_x0029_": "We will tell jokes to the clients[,]Impact_x0020__x0028_Public_x0029_": "Everyone will notice the change.[,]Start_x0020_Time": "2015-11-27T08:38:00-05:00[,]End_x0020_Time": "2015-11-30T00:00:00-05:00[,]Hours": 1
}]
My question is, how can I modify the expression so that PHP will behave like regexpal.com and only get the numbers within quotes and ignore the rest?
Your regex is rather strange, you appear to be trying to put a pattern expression inside a character class [...], which is probably not doing what you'd expect. Furthermore, your regex would match values inside other key/value pairs. Try this instead, which will only match values for the key "Systems_x0020_Changed_IDs":
"Systems_x0020_Changed_IDs":\s+"([^"]*)"
What about just parsing it as the JSON that it is?
$jsons = array('{
"ID": 1050436,
"Title": "THE SKY IS FALLING!!!!",
"Application_x0020_ID": 242,
"Systems_x0020_Changed": "Academic Planning System (APS),\"Documents planning and evaluation processes at UGA that support cont",
"Systems_x0020_Changed_IDs": "39122",
"Status": "New",
"Modified": "2015-10-28T16:14:45.573-04:00",
"Age": 40,
"Description_x0020__x0028_Public_x0029_": "I\'m chicken little and the SKY IS FALLING!",
"Impact_x0020__x0028_Public_x0029_": "The world is going to end!",
"Start_x0020_Time": "2015-10-28T00:00:00-04:00",
"End_x0020_Time": "2015-10-30T00:00:00-04:00",
"Hours": 12
}', '{
"ID": 1050740,
"Title": "This is a Title",
"Application_x0020_ID": 242,
"Systems_x0020_Changed": "EITS Websites,\"EITS departmental web pages.\", GACRC Archival Storage,\"Archival Storage for Research Data\", VPS,\"Mainframe distributed printing system\"",
"Systems_x0020_Changed_IDs": "39223, 39244, 39395",
"Status": "New",
"Modified": "2015-11-05T17:31:13.15-05:00",
"Age": 32,
"Description_x0020__x0028_Public_x0029_": "We will tell jokes to the clients",
"Impact_x0020__x0028_Public_x0029_": "Everyone will notice the change.",
"Start_x0020_Time": "2015-11-27T08:38:00-05:00",
"End_x0020_Time": "2015-11-30T00:00:00-05:00",
"Hours": 1
}');
foreach($jsons as $json){
$json_array = json_decode($json, true);
echo $json_array['Systems_x0020_Changed_IDs'] . "\n";
}
Demo: https://eval.in/481865
If you needed a regex you could do something like:
"Systems_x0020_Changed_IDs":\h*"(([\d+],?\h*)*)"
Demo: https://regex101.com/r/yZ6eM3/1
PHP Usage:
$string = '{
"ID": 1050436,
"Title": "THE SKY IS FALLING!!!!",
"Application_x0020_ID": 242,
"Systems_x0020_Changed": "Academic Planning System (APS),\"Documents planning and evaluation processes at UGA that support cont",
"Systems_x0020_Changed_IDs": "39122",
"Status": "New",
"Modified": "2015-10-28T16:14:45.573-04:00",
"Age": 40,
"Description_x0020__x0028_Public_x0029_": "I\'m chicken little and the SKY IS FALLING!",
"Impact_x0020__x0028_Public_x0029_": "The world is going to end!",
"Start_x0020_Time": "2015-10-28T00:00:00-04:00",
"End_x0020_Time": "2015-10-30T00:00:00-04:00",
"Hours": 12
}, {
"ID": 1050740,
"Title": "This is a Title",
"Application_x0020_ID": 242,
"Systems_x0020_Changed": "EITS Websites,\"EITS departmental web pages.\", GACRC Archival Storage,\"Archival Storage for Research Data\", VPS,\"Mainframe distributed printing system\"",
"Systems_x0020_Changed_IDs": "39223, 39244, 39395",
"Status": "New",
"Modified": "2015-11-05T17:31:13.15-05:00",
"Age": 32,
"Description_x0020__x0028_Public_x0029_": "We will tell jokes to the clients",
"Impact_x0020__x0028_Public_x0029_": "Everyone will notice the change.",
"Start_x0020_Time": "2015-11-27T08:38:00-05:00",
"End_x0020_Time": "2015-11-30T00:00:00-05:00",
"Hours": 1
}';
$regex = '/"Systems_x0020_Changed_IDs":\h*"((?:[\d+],?\h*)*)"/';
preg_match_all($regex, $string, $matches);
print_r($matches[1]);
Output:
Array
(
[0] => 39122
[1] => 39223, 39244, 39395
)
Demo #2: https://eval.in/481871
The answer I was looking for is:
$str = preg_replace('/"((\d+[, ]*)+)"/', "[$1]", $str);
I needed the JSON file as is except for number values as strings. My regex worked after I played with it a little more.
This is a snippet of code inside my JSON parser function, which is working fine with about a dozen or so various JSON files:
The prints are there for current debugging purposes
$this->response = stripslashes($this->response);
print_r($this->response);
$this->response = json_decode($this->response);
print_r($this->response);
The first print gives me the JSON string, and the second print gives me null. Using json_last_error I managed to find out that PHP was refusing to parse the JSON as it was in an invalid syntax.
This is a snipped of the JSON I'm parsing (full thing here), it validates with every validator I can find on Google:
{
"success": 1,
"stores": [
{
"name": "Winton",
"address": "370-374 , Wimborne Road, Bournemouth, Dorset BH92HE",
"telephone": "",
"email": "info#99pstoresltd.com",
"website": "",
"description": "Mon - 09.00-18.00 Tue - 09.00-18.00 Wed - 09.00-18.00 Thu - 09.00-18.00 Fri - 09.00-18.00 Sat - 09.00-18.00 Sun - 10.00-16.00",
"lat": "50.7413",
"lng": "-1.87926",
"titlewebsite": "Website",
"titleemail": "Email",
"titletel": "Telephone",
"titlecontactstore": "Contact this store",
"titlekm": "km",
"titlemiles": "miles",
"cat_name": "",
"cat_img": "",
"img": ""
},
{
"name": "Boscombe",
"address": "The Sovereign Centre, Boscombe, Bournemouth, Dorset BH14SX",
"telephone": "",
"email": "info#99pstoresltd.com",
"website": "",
"description": "Mon - 08.00-18.00 Tue - 08.00-18.00 Wed - 08.00-18.00 Thu - 08.00-18.00 Fri - 08.00-18.00 Sat - 08.00-18.00 Sun - 10.00-16.00",
"lat": "50.7272",
"lng": "-1.83952",
"titlewebsite": "Website",
"titleemail": "Email",
"titletel": "Telephone",
"titlecontactstore": "Contact this store",
"titlekm": "km",
"titlemiles": "miles",
"cat_name": "",
"cat_img": "",
"img": ""
}]
}
I have no idea why this isn't parsing as the JSON looks fine to me! Been staring at this for quite a while now so would be more than happy to here some thoughts on this.
EDIT:
Copy and pasting the data from the first print_r and pushing it through the json_decode works fine. I'm assuming this means there is an issue with where the JSON is originating from which could be messing up encoding or something?
Try this:
json_decode($this->response, true);
From the documentation about the second parameter:
When TRUE, returned objects will be converted into associative arrays.
Source: http://php.net/manual/en/function.json-decode.php
I am trying to print the values based on the key specified by the user..
My javascript object looks like
$test={
"timed_out": false,
"hits": {
"hits": [
{
"_index": "test2",
"_type": "news",
"_source": {
"partnerName": "Accountancy_Age",
"entityCount": 4,
"Categories": {
"Facets": [
{
"count": 1,
"entity": "Company",
"Company": [
{
"Pearson_Plc-Sponsored_Adr": [
{
"count": 1,
"entity": "Pearson"
}
],
"sector": "Communications",
"ticker": "PSO",
"entity": "Pearson Plc-Sponsored Adr",
"type": "ADR"
}
]
},
{
"CorporateAction": [
{
"count": 2,
"entity": "restructuring"
}
],
"count": 2,
"entity": "CorporateAction"
},
{
"count": 1,
"entity": "Persons",
"Persons": [
{
"count": 1,
"entity": "Steven Pearson"
}
]
}
]
},
"Title": "PwC takes on major London oil refinery administration ",
"Tags": "News",
"ParentUrl": "http://www.accountancyage.com/feeds/rss/maxcontentwords/75/category/business-regulation",
"Link": "http://www.accountancyage.com/aa/news/2141170/pwc-takes-major-london-oil-refinery-administration?WT.rss_f=Business+regulation&WT.rss_a=PwC+takes+on+major+London+oil+refinery+administration+",
"SourceName": "Accountancy_Age",
"SentimentResource": "neutral",
"Content": "<div class=\"article_description\" algoscore=\"83\">\n <p algoscore=\"34\"><strong>LONDON'S BIGGEST </strong>oil refinery has been handed over to administrators from PwC by its Swiss parent company.</p>\n <p algoscore=\"37\">Petroplus, which refines 220,000 barrels a day from the Thames, was declared insolvent after the group suffered refinancing issues, a high cost base and high restructuring costs.</p>\n <p algoscore=\"35\">The business has around 60 employees, and supplies aronud a fifth of London and the south-east's 2,000 forecourts.</p>\n <p algoscore=\"40\">"Our immediate priority is to continue to operate the Coryton refinery and the Teeside storage business, without disruption while the financial position is clarified and restructuring options are explored," said PwC joint administrator Steven Pearson.</p>\n <p algoscore=\"38\">"Over coming days we intend to commence discussions with a number of parties including customers, employees, the creditors and the government to secure the future of the Coryton and Teesside sites.</p>\n</div>"
}
},
{
"_index": "test3",
"_type": "news",
"_source": {
"partnerName": "propertyFile 7",
"entityCount": 33,
"Categories": {
"Types": {
"Facets": [
{
"count": 3,
"entity": "Company",
"Company": [
{
"sector": "Basic Materials",
"ticker": "BHP",
"entity": "Bhp Billiton Ltd-Spon Adr",
"Bhp_Billiton_Ltd-Spon_Adr": [
{
"count": 1,
"entity": "BHP Billiton Ltd"
}
],
"type": "ADR"
},
{
"sector": "Communications",
"ticker": "CHL",
"entity": "China Mobile Ltd-Spon Adr",
"type": "ADR",
"China_Mobile_Ltd-Spon_Adr": [
{
"count": 1,
"entity": "China Mobile"
}
]
},
{
"sector": "Energy",
"Royal_Dutch_Shell_Plc-Adr": [
{
"count": 1,
"entity": "Royal Dutch"
}
],
"ticker": "RDS/A",
"entity": "Royal Dutch Shell Plc-Adr",
"type": "ADR"
}
]
},
{
"count": 6,
"entity": "Country",
"Country": [
{
"region": "Asia",
"Taiwan": [
{
"count": 1,
"entity": "Taiwan"
}
],
"index": "TAIWAN TAIEX INDEX",
"entity": "Taiwan",
"currency": "Dollar (TWD)"
},
{
"region": "Latin Americas",
"index": "BRAZIL BOVESPA INDEX",
"Brazil": [
{
"count": 1,
"entity": "Brazil"
}
],
"entity": "Brazil",
"currency": "Real (BRL)"
},
{
"region": "East Europe",
"index": "ISE NATIONAL 100 INDEX",
"entity": "Turkey",
"Turkey": [
{
"count": 1,
"entity": "Turkey"
}
],
"currency": "Lira (TRY)"
},
{
"region": "Europe",
"index": "BLOOMBERG EUROPEAN 500 , Euro Stoxx 50 Pr",
"entity": "Europe",
"Europe": [
{
"count": 1,
"entity": "Europe"
}
],
"currency": "Euro (EUR)"
},
{
"region": "Asia",
"index": "CSI 300 INDEX , SHANGHAI SE COMPOSITE , SHENZHEN SE COMPOSITE IX , SSE COMPONENT STOCK IX",
"entity": "China",
"China": [
{
"count": 2,
"entity": "China"
}
],
"currency": "Yuan Renminbi (CNY)"
}
]
},
{
"AnalystLevel": [
{
"count": 1,
"entity": "Buy"
},
{
"count": 1,
"entity": "hold"
},
{
"count": 4,
"entity": "market"
}
],
"count": 6,
"entity": "AnalystLevel"
},
{
"MoneyEvent": [
{
"count": 1,
"entity": "Fund managers look at all sizes of companies and \r\nbase their selections on an index of companies that have paid at least $5 \r\nmillion in dividends over the past year."
}
],
"count": 1,
"entity": "MoneyEvent"
},
{
"DateEvent": [
{
"count": 1,
"entity": "CHICAGO, June 1 (Reuters) - Finding consistent total stock returns has \r\nalways been a challenge."
},
{
"count": 1,
"entity": "Many, if not most, of these funds, it should be noted, were touted last \r\nyear as part of a growing group of \"low-volatility\" stock funds."
},
{
"count": 1,
"entity": "The fund invests in companies \r\namong the top 100 dividend payers that have had payouts in the previous \r\nthree years."
},
{
"count": 1,
"entity": "Yet the insurer is \r\nthe top holding in the SPDR S&P International Dividend ETF , paying a 5.38 \r\npercent dividend yield as of June 1."
}
],
"count": 4,
"entity": "DateEvent"
},
{
"count": 5,
"LocationEvent": [
{
"count": 1,
"entity": "And some of the best sectors for high-dividend players are \r\nfar from Wall Street."
},
{
"count": 1,
"entity": "But even as the euro zone beast continues to flair \r\nits nostrils and U.S. employment wheezes, there are stocks that are worthy \r\ncontenders, particularly ones that pay dividends."
},
{
"count": 1,
"entity": "That's \r\nroughly twice the population of the U.S. already."
},
{
"count": 1,
"entity": "These funds can be volatile and will be impacted if more European countries \r\nslip into recession, the U.S. falters or the Eurozone banking crisis isn't \r\nresolved."
},
{
"count": 1,
"entity": "To find dividend players in emerging markets, I suggest the WisdomTree \r\nEmerging Markets Equity Income fund, which gives you exposure to China, \r\nBrazil, Taiwan and Turkey."
}
],
"entity": "LocationEvent"
},
{
"count": 3,
"CompanyEvent": [
{
"count": 1,
"entity": "China Mobile, the largest cellphone carrier in the People's \r\nRepublic, has more than 600 million subscribers - and is growing."
},
{
"count": 1,
"entity": "The Admiral Group, a U.K.-based \r\nauto insurance company, for example, is hardly in a league with the oil \r\nproducer Royal Dutch Shell in terms of name recognition."
},
{
"count": 1,
"entity": "Then you'd want a \r\ncompany like BHP Billiton Ltd. ), one of the world's largest natural \r\nresources companies."
}
],
"entity": "CompanyEvent"
},
{
"count": 1,
"entity": "AnalystAction",
"AnalystAction": [
{
"count": 1,
"entity": "Buy"
}
]
},
{
"count": 2,
"entity": "PercentEvent",
"PercentEvent": [
{
"count": 1,
"entity": "Europe's largest oil producer reported \r\nthat its earnings were up 11 percent in the first quarter."
},
{
"count": 1,
"entity": "Shell, by the way, is no slouch in the dividend department either, paying \r\n5.53 percent as of the same date."
}
]
},
{
"count": 1,
"entity": "Person",
"Person": [
{
"count": 1,
"entity": "John Wasik"
}
]
},
{
"count": 1,
"entity": "PersonEvent",
"PersonEvent": [
{
"count": 1,
"entity": "By John Wasik"
}
]
}
]
}
},
"Title": "Where in the world are dividends good?",
"ParentUrl": "http://feeds.reuters.com/reuters/blogs/JohnWasik?format=xml",
"Tags": "Blog",
"Link": "http://www.reuters.com/article/2012/06/01/column-wasik-worlddividends-idUSL1E8H15SF20120601?feedType=RSS&feedName=everything&virtualBrandChannel=11563",
"SourceName": "Reuters",
"SentimentResource": "positive",
"Content": "<span id=\"articleText\" algoscore=\"413\"><p></p><span class=\"focusParagraph\"></span><p>By John Wasik</p><p>CHICAGO, June 1 (Reuters) - Finding consistent total stock returns has always been a challenge. But even as the euro zone beast continues to flair its nostrils and U.S. employment wheezes, there are stocks that are worthy contenders, particularly ones that pay dividends. While they don't eliminate market risk, dividends can bolster total return in skittish equity markets. And some of the best sectors for high-dividend players are far from Wall Street.</p><p>For long-term investing, think commodities, energy, utilities and non-banking financial services. Banking is still touchy, but insurance is a safer bet.</p><p>Established, brand-name stocks often pay large dividends, but that doesn't mean they should dominate your portfolio. The Admiral Group, a U.K.-based auto insurance company, for example, is hardly in a league with the oil producer Royal Dutch Shell in terms of name recognition. Yet the insurer is the top holding in the SPDR S&P International Dividend ETF , paying a 5.38 percent dividend yield as of June 1.</p><p>Shell, by the way, is no slouch in the dividend department either, paying 5.53 percent as of the same date. Europe's largest oil producer reported that its earnings were up 11 percent in the first quarter.</p><p>The international dividend strategy is often rooted in sectors in which profits are consistent and growing. That translates into steady dividend growth year after year, although the sectors that are favored for stock-price appreciation will vary.</p><p>Let's say you were long in commodities, which isn't a bad play considering the demand for raw materials from developing countries. Then you'd want a company like BHP Billiton Ltd. ), one of the world's largest natural resources companies. BHP mines aluminum, copper, coal, iron ore, nickel, silver and uranium and also has oil and gas reserves.</p><p>Another growth sector is telecommunications, particularly in emerging economies. China Mobile, the largest cellphone carrier in the People's Republic, has more than 600 million subscribers - and is growing. That's roughly twice the population of the U.S. already.</p><p>A key part of the global dividend strategy is to stay in sectors that are likely to continue dividend growth. That's why exchange-traded funds make the most sense when investing in these companies. The funds can hold broad indexes of dividend payers so you don't have to guess which companies will maintain or raise their payouts. ETFs also blunt risk, since unusually high dividends can be a sign of a company's financial distress.</p><p>To find dividend players in emerging markets, I suggest the WisdomTree Emerging Markets Equity Income fund, which gives you exposure to China, Brazil, Taiwan and Turkey. Fund managers look at all sizes of companies and base their selections on an index of companies that have paid at least $5 million in dividends over the past year. An alternative is the SPDR S&P Emerging Markets Dividend ETF.</p><p>If you prefer a focus on more developed markets, then consider the iShares Dow Jones International Dividend Index ETF . The fund invests in companies among the top 100 dividend payers that have had payouts in the previous three years. A similar fund is the PowerShares International Dividend Achievers Portfolio.</p><p>Many, if not most, of these funds, it should be noted, were touted last year as part of a growing group of "low-volatility" stock funds. While I think that has been a misnomer because it implies that these vehicles won't be hit by general market declines - they certainly will - they deserve a place in your portfolio.</p><p>When selecting a global dividend-stock fund, keep in mind that they won't insulate you from market risk and they are not bond funds.</p><p>These funds can be volatile and will be impacted if more European countries slip into recession, the U.S. falters or the Eurozone banking crisis isn't resolved. They also are subject to sector risk. If they are over concentrated in say, energy, and that sector is sold off in a market correction, then you will see declines in share prices. Buy them to augment your current stock positions and to boost income, but they shouldn't be core holdings.</p></span>",
"ContentHash": 783187784,
"LinkObjects": {
"LinkObjects": [
{
"Link": "http://blogs.reuters.com/search/journalist.php?edition=us&n=john.wasik&",
"Object": "John Wasik"
}
]
}
}
}]}};
what Im trying to achieve here is that if the user specifies wordCount, then it should list out all the occurences of wordCount in the json.
My code looks like,
$.ajax({
url:"/elasticsearch-head/lib/es/queryManipulate.php",
type: 'POST',
datatype: 'json',
data: { index: _index_select, category: _field_select},
success:function(jsonQuery)
{
//alert(jsonQuery);
}
});
<?php
$index=$_POST["index"];
$selectCategory=$_POST["category"];
$url="http://localhost:9200/".$index."//_search";
$object=json_decode($_POST["field"]);
$fields=array();
$fields = explode(',',$selectCategory);
$results = array();
for ($from = 0; $from <50; $from+=10){
$object->from=$from;
$requestJSON=json_encode($object);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestJSON);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resultJSON= curl_exec($ch); // equivalent of our JSON string that Ive shown above
$resultObject = json_decode($resultJSON);
curl_close ($ch);
$hits = $resultObject->hits->hits;
$m=0;
for($j=0 ; $j < sizeOf($hits) ; $j++){
$result = array();
for($i=0 ; $i< sizeOf($fields) ; $i++){
if($fields[$i]=="Categories->Types->Facets")
{
$source = $hits[$j]->_source->Categories->Types->Facets;
//echo $m++ . ";" .sizeof($source)."<br>";
for($k=0; $k < sizeof($source); $k++)
{
//echo $fields[$i];
//echo json_encode($source[$k]->entity) ."<br><br>";
$result[$j]->{$fields[$i]} = json_encode($source[$k]->entity);
//echo $result[$j]->{$fields[$i]};
}
}
else
{
echo "test1";
$source = $hits[$j]->_source;
$result[$j]->{$fields[$i]} = json_encode($source->{$fields[$i]});
}
}
$results=array_merge($results,$result);
}
}
for($j=0 ; $j < sizeOf($fields) ; $j++) {
echo $fields[$j].",";
}
echo "<br>";
for($j=0 ; $j < sizeOf($results) ; $j++) {
$result = $results[$j];
$line="";
for($i=0 ; $i< sizeOf($fields) ; $i++){
#echo var_dump($result);
$field = $fields[$i];
$line.=$result->{$field}.",";
}
echo $line."<br>";
}
?>
This will work if the input is not array, if we give input an array say Company fpr exaample, and I want to output the items listed in that array, how am I gonna approach that?
Try something like this:
$output = null;
array_walk_recursive($array, "callback", $output);
function callback ($value, $key, &$output)
{
if ($key == 'wordCount')
{
$output .= $value;
}
}