I have a JSON array like this:
[
{
"title": " Bones of the Hills (Conqueror #3) ",
"author": "Conn Iggulden",
"format": "Hardcover",
"pages": "518",
"rating": "4.29",
"image": "http://d.gr-assets.com/books/1347616868l/3276637.jpg"
}
]
Sometimes, (not always) the title string has a link in it. How can I remove the link and everything in it? I don't even want the text inside the anchor. I want to end up with JUST "Bones of the Hills" as the title. How can I do this in php? I have googled loads, but nothing seemed to work.
You can use php built in function strip_tags() on title, it will remove all html elements from title including link
You can use strip_tag() function to avoid this error
$str='[{"title": " Bones of the Hills (Conqueror #3) ","author": "Conn Iggulden","format": "Hardcover",';
$str.='"pages": "518","rating": "4.29","image": "http://d.gr-assets.com/books/1347616868l/3276637.jpg"}]';
echo $str2=strip_tags($str);
$array=json_decode($str2);
print_r($array);
first of all your json array is incorrect , check this
[
{
"title": " "title": " Bones of the Hills (Conqueror #3) ",
"author": "Conn Iggulden",
"format": "Hardcover",
"pages": "518",
"rating": "4.29",
"image": "http://d.gr-assets.com/books/1347616868l/3276637.jpg"
}
]
use "title": " Bones of the Hills (Conqueror #3) "
instead of
<a href="/series/44108-conqueror" class="greyText"
then
$arr = json_decode($json,true);
$arr['title'] = preg_replace("/<a.+?href.+?>.+?<\/a>/is","",$arr['title']);
var_dump($arr['title']);
now your title will be
string(20) " Bones of the Hills "
Related
This question already has answers here:
PHP replace wildcards (%s, %d) in string with vars
(2 answers)
Closed 3 years ago.
I've got a JSON file which looks like this
{
"facebook": {
"icon": "fab fa-facebook",
"title": "Facebook",
"url": "https://facebook.com/%s"
},
"instagram": {
"icon": "fab fa-instagram",
"title": "Instagram",
"url": "https://instagram.com/%s"
}
}
So I'm getting users social links from a form, but only the user's ID of social link eg.https://facebook.com/ID. I'm storing the users ID in JSON file in database. I'm using PHP. How do I add the users ID in that '%s' and display the link.
To put together the information using the JSON data you have, you would use either sprintf() or printf() (the only difference being the printf() directly outputs the data sprintf() returns a string). The information on the manual pages shows how things like %s works.
So the code would look something like...
$id = 123;
$userName = "User name";
$json = '{
"facebook": {
"icon": "fab fa-facebook",
"title": "Facebook",
"url": "https://facebook.com/%s"
},
"instagram": {
"icon": "fab fa-instagram",
"title": "Instagram",
"url": "https://instagram.com/%s"
}
}';
$socialMedia = json_decode( $json, true );
echo echo '<a href="'.sprintf($socialMedia["facebook"]["url"], $id).'">'.
$userName.'</a>';
Which outputs...
User name
For example. I want to get coordinates of all node buildings in bbox.
PHP
$queryBuildings="[out:json];node['building']({$y1},{$x1},{$y2},{$x2});out;";
$data = file_get_contents("http://overpass-api.de/api/interpreter?data={$queryBuildings}")
One element from result:
{
"type": "node",
"id": 29537155,
"lat": 54.6744568,
"lon": -2.1421066,
"tags": {
"building": "house",
"description": "Abandoned (2007). Associate with lead mine workings above it?",
"name": "Flushiemere House"
}
}
I want to get only lon and lat fields it's possible?
You can use skeleton print mode (out skel) which omits all tags, thus being slightly shorter. So your request should become: [out:json];node['building']({$y1},{$x1},{$y2},{$x2});out skel;
Currently csv output mode ([out:csv]) is the only mode where you can select the fields to be shown.
<?php
$data = '{
"type": "node",
"id": 29537155,
"lat": 54.6744568,
"lon": -2.1421066,
"tags": {
"building": "house",
"description": "Abandoned (2007). Associate with lead mine workings above it?",
"name": "Flushiemere House"
}
}';
$test = json_decode($data);
var_dump($test->lon);
First use json_decode to parse the response body:
$parsed_data = json_decode($data);
Then you can access the various fields like so:
$lat = $parsed_data->lat;
$lon = $parsed_data->lon;
I am using PHP on shared server to access external site via API that is returning JSON containing 2 levels of data (Level 1: Performer & Level 2: Category array inside performer). I want to convert this to multidimensional associative array WITHOUT USING json_decode function (it uses too much memory for this usage!!!)
Example of JSON data:
[
{
"performerId": 99999,
"name": " Any performer name",
"category": {
"categoryId": 99,
"name": "Some category name",
"eventType": "Category Event"
},
"eventType": "Performer Event",
"url": "http://www.novalidsite.com/something/performerspage.html",
"priority": 0
},
{
"performerId": 88888,
"name": " Second performer name",
"category": {
"categoryId": 88,
"name": "Second Category name",
"eventType": "Category Event 2"
},
"eventType": "Performer Event 2",
"url": "http://www.novalidsite.com/somethingelse/performerspage2.html",
"priority": 7
}
]
I have tried to use substr and strip the "[" and "]".
Then performed the call:
preg_match_all('/\{([^}]+)\}/', $input, $matches);
This gives me the string for each row BUT truncates after the trailing "}" of the category data.
How can I return the FULL ROW of data AS AN ARRAY using something like preg_split, preg_match_all, etc. INSTEAD of the heavy handed calls like json_decode on the overall JSON string?
Once I have the array with each row identified correctly, I CAN THEN perform json_decode on that string without overtaxing the memory on the shared server.
For those wanting more detail about json_decode usage causing error:
$aryPerformersfile[ ] = file_get_contents('https://subdomain.domain.com/dir/getresults?id=1234');
$aryPerformers = $aryPerformersfile[0];
unset($aryPerformersfile);
$mytmpvar = json_decode($aryPerformers);
print_r($mytmpvar);
exit;
If you have a limited amount of memory, you could read the data as a stream and parse the JSON one piece at a time, instead of parsing everything at once.
getresults.json:
[
{
"performerId": 99999,
"name": " Any performer name",
"category": {
"categoryId": 99,
"name": "Some category name",
"eventType": "Category Event"
},
"eventType": "Performer Event",
"url": "http://www.novalidsite.com/something/performerspage.html",
"priority": 0
},
{
"performerId": 88888,
"name": " Second performer name",
"category": {
"categoryId": 88,
"name": "Second Category name",
"eventType": "Category Event 2"
},
"eventType": "Performer Event 2",
"url": "http://www.novalidsite.com/somethingelse/performerspage2.html",
"priority": 7
}
]
PHP:
$stream = fopen('getresults.json', 'rb');
// Read one character at a time from $stream until
// $count number of $char characters is read
function readUpTo($stream, $char, $count)
{
$str = '';
$foundCount = 0;
while (!feof($stream)) {
$readChar = stream_get_contents($stream, 1);
$str .= $readChar;
if ($readChar == $char && ++$foundCount == $count)
return $str;
}
return false;
}
// Read one JSON performer object
function readOneJsonPerformer($stream)
{
if ($json = readUpTo($stream, '{', 1))
return '{' . readUpTo($stream, '}', 2);
return false;
}
while ($json = readOneJsonPerformer($stream)) {
$performer = json_decode($json);
echo 'Performer with ID ' . $performer->performerId
. ' has category ' . $performer->category->name, PHP_EOL;
}
fclose($stream);
Output:
Performer with ID 99999 has category Some category name
Performer with ID 88888 has category Second Category name
This code could of course be improved by using a buffer for faster reads, take into account that string values may themselves include { and } chars etc.
You have two options here, and neither of them include you writing your own decoder; don't over-complicate the solution with an unnecessary work-around.
1) Decrease the size of the json that is being decoded, or
2) Increase the allowed memory on your server.
The first option would require access to the json that is being created. This may or may not be possible depending on if you're the one originally creating the json. The easiest way to do this is to unset() any useless data. For example, maybe there is some debug info you won't need, so you can do unset($json_array['debug']); on the useless data.
http://php.net/manual/en/function.unset.php
The second option requires you to have access to the php.ini file on your server. You need to find the line with something like memory_limit = 128M and make the 128M part larger. Try increasing this to double the value already within the file (so it would be 256M in this case). This might not solve your problem though, since large json data could still be the core of your problem; this only provides a work-around for inefficient code.
{
"name": "2Pac",
"album": "All Eyez on Me",
"track": "All Eyez on Me",
"duration": "5:08",
"trackNo": ""
},
{
"name": "2Pac",
"album": "2Pac Greatest Hits",
"track": "Keep Ya Head Up",
"duration": "4:24",
"trackNo": "1"
},
{
"name": "2Pac",
"album": "2Pac Greatest Hits",
"track": "2 Of Amerikaz Most Wanted",
"duration": "4:07",
"trackNo": "2"
},
{
"name": "50 Cent",
"album": "Get Rich Or Die Tryin%27",
"track": "P.I.M.P.",
"duration": "4:10",
"trackNo": "11"
},
{
"name": "50 Cent",
"album": "Get Rich Or Die Tryin%27",
"track": "Like My Style",
"duration": "3:13",
"trackNo": "12"
},
I have lots of json data formatted this way and was looking for a way to manipulate the data so that it only has one artist name and then the albums for that artist then songs within each album. PHP would be fine so I can convert things, Any help would be appreciated.
Use these:
json_decode
array_map, array_filter, for loops, what you like
json_encode
Basically it boils down to:
parse
mangle
format
I'll leave the exercise to you, but browsing these functions and similar questions here should get you started. If you have anything to show then, you may ask for more specific help.
I'm trying to match a form supplied UTC time and form supplied event name string with an array read in from a file. The problem is that it seems to always match even when it shouldn't. The format of the file will always be constant, so I know I'll be looking for a value within double quotes, so after failing to get results with strpos(), I tried preg_match...and now match everything. Code and example output follow ($utc and $event_name)are already set and correct when we get here):
$match1 = "/\"{$utc}\"/";
$match2 = "/\"{$event_name}\"/";
print "Match Values: $match1, $match2<p>";
foreach($line_array as $key => $value) {
print "Value = $value<p>";
if ((preg_match($match1,$value) == 1) and (preg_match($match2,$value) == 1))
{
print "Case 1 - False<p>";
} else {
print "Contains targets: $value<p>";
//code to act on hit will go here
}
}
And here's what comes back:
Match Values: /"1371033000000"/, /"Another test - MkII "/
Value = { "date": "1357999200000", "type": "meeting", "title": "Plant and Animal Genome Conference, San Diego, CA", "description": "NCGAS to present at Plant and Animal Genome Conference, San Diego, CA", "url": "http://www.event1.com/" }
Contains targets: { "date": "1357999200000", "type": "meeting", "title": "Plant and Animal Genome Conference, San Diego, CA", "description": "NCGAS to present at Plant and Animal Genome Conference, San Diego, CA", "url": "http://www.event1.com/" }
Value = { "date": "1357693200000", "type": "meeting", "title": "Testing Addition", "description": "This is a fake event.", "url": "http://pti.iu.edu" }
Contains targets: { "date": "1357693200000", "type": "meeting", "title": "Testing Addition", "description": "This is a fake event.", "url": "http://pti.iu.edu" }
Value = { "date": "1371033000000", "type": "meeting", "title": "Another test - MkII", "description": "This is a fake event.", "url": "http://pti.iu.edu" }
Contains targets: { "date": "1371033000000", "type": "meeting", "title": "Another test - MkII", "description": "This is a fake event.", "url": "http://pti.iu.edu" }
I should only be matching the last one, but they all match. I've been playing with the regex and can't seem to find the right magic.
Simplified it and got what I was after:
foreach($line_array as $key => $value) {
print "Value = $value<p>";
if (preg_match("/$utc/",$value) and preg_match("/$event_time/",$value))
{
print "Contains targets: $value<p>";
} else {
print "Case 1 - False<p>";
//code to act on hit will go here
}
}
But answer 2 got me in the right direction. Thanks, Ian!
You don't need to do anything weird inside a double-quoted string, just drop your variable in as is...
$match1 = "/$utc/";
$match2 = "/$event_name/";
I suspect your regexes are looking for zero-length strings.
Also, this line doesn't need so many parentheses...
if (preg_match($match1,$value) == 1 and preg_match($match2,$value) == 1) {
[...]
}