How get values after " , " (comma) in php string? - php

Am importing live data from an XML to my live wordpress website. Am using WP-ALL-IMPORT and i have a situation here
I need to import location for my post but my XML gives the coordinates as a single strong ( not longitude and latitude separately) like below
<geopoints>55.25424242,25.15498337</geopoints>
So how do i remove the value after and before the "," comma with [str_replace]
or is there any other way to do this

if you have the value of geopoint tag
the you can use explode
$myGeoPointFromXml = '55.25424242,25.15498337';
$myRes = explode(',', $myGeoPointFromXml ); // this return an array for each value seprated by comma
echo $myRes[0] // show 55.25424242
echo $myRes[1] // show 25.15498337

Related

Trying to grab value from html page but getting template back not the value - php

I am making a price crawler for a project but am running into a bit of an issue. I am using the below code to extract values from an html page:
$content = file_get_contents($_POST['url']);
$resultsArray = array();
$sqlresult = array();
$priceElement = explode( '<div>value I want to extract</div>' , $content );
Now when I use this to get certain elements I only get back
Finance: {{value * value2}}
I want to get the actual value that would be displayed on the screen e.g
Finance: 7.96
The other php methods I have tried are:
curl
file_get_html(using simple_html_dom library)
None of these work either :( Any ideas what I can do?
You just set the <div>value I want to extract</div> as a delimiter, which means PHP looks for it to separate your string to array whenever this occurs.
In the following code we use , character as a delimiter:
<?php
$string = "apple,banana,lemon";
$array = explode(',', $string);
echo $array[1];
?>
The output should be this:
banana
In your example you set the value you want to extract as a delimiter. That's why this happens to you. You'll need to set a delimiter between your string you want to obtain and other string you won't need at the moment.
For example:
<?php
$string = "iDontNeedThis-dontExtractNow-value I want to extract-dontNeedEither";
$priceElement = explode('-', $string);
echo "<div>".$priceElement[2]."</div>";
?>
The code should output this to your HTML page:
<div>value I want to extract</div>
And it will appear on your page like this:
value I want to extract
If you don't need to save the whole array in a variable, you can save the one index of it to variable instead:
$priceElement = explode('-', $string)[2];
echo $priceElement;
This will save only value I want to extract so you won't have to deal with arrays later on.

php : parse xml file Multi line strings

I need to form a table for each road with a shape_leng and a coordinates(multilinestring) columns for each road there can be any number of lines for a road i need to save them in one row
Xml file is of this format: a few roads are multiline strings, and a few others have only one line:
And I have tried to parse it
(Note that shape_leng is single for a road, but coordinate lines can be single or many for a road.)
So I am unable to add them in a particular order like shape_leng and coordinates.
If you want to insert all coordinates into a single database row, I think you have to construct the XPath and loop a bit differently. Loop through the roads, then use XPath to get all coordinates belonging to that road. Eg:
// get all the roads and loop through them
$roads = $xml->xpath("//e:featureMember/b:AA_ROAD");
$i=0;
while(isset($roads[$i]))
{
// get the coordinates for the current road
$coordinates = $roads[i]->xpath("/b:the_geom/e:MultiLineString/e:lineStringMember/e:LineString/e:coordinates");
$shapel = $roads[i]->xpath("/b:SHAPE_Leng");
// add a second loop to concatinate all the $coordinates
$j=0;
while (isset($coordinates[$j])) {
// TODO concatinate coordinates
}
// insert the row
$b=mysql_query("INSERT IGNORE INTO `new`.`road1` (`coordstr`, `shapeleng`) values (GEOMFROMTEXT(concat('MULTILINESTRING ($a )')), '$shapel[$i]') ");
$i++;
echo "<br />";
echo $i;
}

MYSQL fetch a xml string, without converting/interpreting

Simple requirement: I want to store a flat unchanged XML strings into a MySQL-DB and then fetch the string itself via php with the tags (i.e. <tag>1234</tag>).
Problem: When I fetch the string, I get the values not the entire XML string.
I store <tag>1243</tag> (done via PHPmyAdmin) then I fetch (see code below) and echo the result I get 1234 not <tag>1234</tag>.
$query = "SELECT * FROM " . $my_table_with_flat_xml_string;
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$xml_flat_file_with_the_tags_please = $row[0];
echo " ( " . $tags. ")";
}
Help!
The String fetched from the database is <tag>1234</tag> as you put it into the database. MySQL does not interpret or parse XML input as long as you don't tell it to.
But you only echo it without escaping the < and >-chars, so your browser thinks, this would be a HTML-Element.
You can use something like the var_dump()-function to print out your fetched value or you escape the brackets by using the htmlspecialchars()-function.
Every node has a "name" (e.g. "tag") and a value (e.g. "1234", or perhaps "empty").
You've got the value.
You simply want to store the name, too. Twice.
By creating the string "<" . $name . ">" . $value . ""
There are several different ways to get $name and $value - it all depends on exactly how you're parsing your XML file.
Here's an excellent tutorial that gives you details on using XML from PHP:
http://www.ibm.com/developerworks/xml/library/x-xmlphp1/index.html
http://www.ibm.com/developerworks/xml/library/x-xmlphp2/index.html
http://www.ibm.com/developerworks/xml/library/x-xmlphp3/index.html

Splitting value of drop down selection into two variables? (PHP/HTML)

So I've got a website with two HTML drop-down lists- one is a list of US states, the other is a list of the cities/towns in the selected state. As of right now, I have an HTML file for each state, and they all have the options listed as such:
<option value="44.729932, -72.381758">Albany</option>
<option value="44.976728, -73.30257">Alburg</option>
The values are the coordinates (latitude, longitude) of each town. When I hit "search", the form data is sent to a PHP script for SimpleGeo (a location database company- amazing, btw)- the purpose of selecting the town is to provide values for $lat and $lon in this part of the PHP script, which is sent to SimpleGeo for every query:
$q = $_GET['q'];
$lat = 44.729932;
$lon = -72.381758;
$args = array('q' => $q, 'num' => 25, 'category' => Restaurant, 'radius' => 25);
$results = $client->getPlaces($lat, $lon, $args);
The part that can't change is the "getPlaces($lat, $lon, $args);" part because for some reason when I replace $lat and $lon with $coordinates and then replace their values with:
$coordinates = $_GET['city']; ('city' is the name and id of my city/town lists)
It doesn't see it as a valid query. Meanwhile, if you replace "$lat, $lon" with numbers as the coordinates, it understands perfectly.
... I just need to split up my values, either in the HTML files themselves, or in the PHP script by recognizing that ", " means the latitude value has ended and the longitude value has started. I don't know how it should be done, I just know that $lat and $lon have to equal the values set by my HTML files- one file for every state, about 500 options on average per file... How do I make it recognize something like "44.729932, -72.381758" as $lat and $lon?! Or alternatively, how do I make my drop down list pass on the values for lat and lon if I make the options look like this:
<option lat="44.976728" lon="-73.30257">Alburg</option>
Thanks for reading, sorry it's so long! It's 2:50AM, my eyes are bleeding! :P Help is MUCH appreciated...
You can split your option's value to get the latitude and longitude.
Validate your field with a regex like -?[0-9]+\.[0-9]+, -?[0-9]+\.[0-9]+, then explode it and get the two values :
list($lat, $lon) = explode(", ", $_GET['city']);
Here the separator is , including the space, to remove it btw.
You could try this...
if (isset($_GET['location']) AND strpos($_GET['location'], ', ') !== FALSE) {
list($latitude, $longitude) = explode(', ', $_GET['location']);
}
...though this will also split successfully if someone sends you something funny like hello -4.3, 3.1 bye!.
Ideone.
Alternatively, you could use this regex to validate it and extract the values.
if ($location = filter_input(INPUT_GET, 'location')) {
preg_match('/^(?P<latitude>-?\d+\.\d+), (?P<longitude>-?\d+\.\d+)\z/', $location, $matches);
$latitude = $matches['latitude'];
$longitude = $matches['longitude'];
}
Ideone.
The issue above of extra data either side won't be an issue with the regex.
I'd advise that you use a unique ID as the option's value attribute and then load the latitude and longitude for the selected town from your database based on the ID the user selects.
If you insist in doing it this way, then you can use explode() to split the returned value.

Insert string between two markers

I have a requirement to insert a string between two markers.
Initially I get a sting (from a file stored on the server) between #DATA# and #END# using:
function getStringBetweenStrings($string,$start,$end){
$startsAt=strpos($string,$start)+strlen($start);
$endsAt=strpos($string,$end, $startsAt);
return substr($string,$startsAt,$endsAt-$startsAt);
}
I do some processing and based on the details of the string, query for some records. If there are records I need to be able to append them at the end of the string and then re-insert the string between #DATA# and #END# within the file on the server.
How can I best achieve this?
Is it possible to insert a record at a time in the file before #END# or is it best to manipulate the string on the server and just re-insert over the existing string in the file on the server?
Example of Data:
AGENT_REF^ADDRESS_1^ADDRESS_2^ADDRESS_3^ADDRESS_4^TOWN^POSTCODE1^POSTCODE2^SUMMARY^DESCRIPTION^BRANCH_ID^STATUS_ID^BEDROOMS^PRICE^PROP_SUB_ID^CREATE_DATE^UPDATE_DATE^DISPLAY_ADDRESS^PUBLISHED_FLAG^LET_RENT_FREQUENCY^TRANS_TYPE_ID^NEW_HOME_FLAG^MEDIA_IMAGE_00^MEDIA_IMAGE_TEXT_00^MEDIA_IMAGE_01^MEDIA_IMAGE_TEXT_01^~
#DATA#
//Property records would appear here and match the string above, each field separated with ^ and terminating with ~
//Once the end of data has been reached, it will be fully terminated with:
#END#
When I check for new properties, I do the following:
Get all existing properties between #DATA# and #END#
Get the IDs of the properties and query for new properties which don't match these IDs
I then need to re-insert the new properties before #END# but after the last property in the file.
The structure of the file is a Rightmove BLM file.
Just do an str_replace() of the old data with the new:
$str = str_replace('#DATA#'.$oldstr.'#END#', '#DATA#'.$newstr.'#END#', $str);
I would extract the data in 3 steps:
1) Extract the data from the file:
<?php
preg_match("/#DATA#(.+)#END#/s", $string, $data);
?>
2) Extract each row of data:
<?php
preg_match_all("/((?:.+\^){2,})~/", $data[1], $rows, PREG_PATTERN_ORDER);
// The rows with data will be stored in $rows[1]
?>
3) Manipulate the data in each row or add new rows:
<?php
//Add
// Add new row to the end of the array
$data[1][] = implode('^', $newRowArray);
//Use
// Creates an array with all the data from the row '0'
$rowData = preg_split("/\^/", $data[1][0], -1, PREG_SPLIT_NO_EMPTY);
//Save the changes
//$newData should be all the rows together (with the '~' at the end of each row)
//$string is the original string with all the information
$file = preg_replace("/(#DATA#\r?\n).+(\r?\n#END#)/s", "\1".$newData."\2", $string);
I hope this can help you in your problem.

Categories