i am doing something wrong with my foreach cycle. But looks my knowledge is not enugh to figure out what's wrong. My code is pretty simple:
$xnl_file = "xml.xml";
$xml = simplexml_load_file($xnl_file);
$my_file = 0;
foreach ($xml as $value){
var_dump($value);
$CountryOrganizationId = "<CountryOrganizationId>".$xml->Partnership->CountryOrganizationId."</CountryOrganizationId>";
$PartnershipId = "<PartnershipId>".$xml->Partnership->PartnershipId."</PartnershipId>";
$OwnerId = "<OwnerId>".$xml->Partnership->OwnerId."<OwnerId>";
$PartnerIdList = "<PartnerIdList><String>".$xml->Partnership->PartnerIdList->String."</String></PartnerIdList>";
$CountryOrganizationId_contact = "<Contract><CountryOrganizationId>".$xml->Partnership->Contract->CountryOrganizationId."</CountryOrganizationId>";
$ContractId = "<ContractId>".$xml->Partnership->Contract->ContractId."</ContractId>";
$data = "<Partnership>".$CountryOrganizationId.$PartnershipId.$OwnerId.$PartnerIdList.$CountryOrganizationId_contact.$ContractId.$Role1.$Category1.$Rate1.
$Role2.$Category2.$Rate2.$Role3.$Category3.$Rate3."</Partnership>";
echo $data;
}
I am getting data from XML and try to parse it on multiple one, but this just copy same data again and again. I am not sure what i am doing wrong. In my opinion data should rewrite each other every time cycle is doing same but they are not changing. At echo $data i get as many results as i should, problem is just they are same.
If I var_dump $value at start i get nice result that data are coming to cycle but why the output is the same all the time?
Please can somebody give me advise?
Thanks
The $value variable is never used, you're always using the $xml. Try it like:
$xnl_file = "xml.xml";
$xml = simplexml_load_file($xnl_file);
$my_file = 0;
foreach ($xml as $value){
var_dump($value);
$CountryOrganizationId = "<CountryOrganizationId>" . $value->CountryOrganizationId . "</CountryOrganizationId>";
$PartnershipId = "<PartnershipId>" . $value->PartnershipId . "</PartnershipId>";
$OwnerId = "<OwnerId>" . $value->OwnerId . "<OwnerId>";
$PartnerIdList = "<PartnerIdList><String>" . $value->PartnerIdList->String . "</String></PartnerIdList>";
$CountryOrganizationId_contact = "<Contract><CountryOrganizationId>" . $value->Contract->CountryOrganizationId . "</CountryOrganizationId>";
$ContractId = "<ContractId>" . $value->Contract->ContractId . "</ContractId>";
$data = "<Partnership>" . $CountryOrganizationId . $PartnershipId . $OwnerId . $PartnerIdList . $CountryOrganizationId_contact .
$ContractId . $Role1 . $Category1 . $Rate1 . $Role2 . $Category2 . $Rate2 . $Role3 . $Category3 . $Rate3 .
"</Partnership>"afdsf
echo $data;
}
Concat $data to its previous value { $data .= "......"}
foreach ($xml as $value)
{
var_dump($value);
$CountryOrganizationId = "<CountryOrganizationId>".$xml->Partnership->CountryOrganizationId."</CountryOrganizationId>";
$PartnershipId = "<PartnershipId>".$xml->Partnership->PartnershipId."</PartnershipId>";
$OwnerId = "<OwnerId>".$xml->Partnership->OwnerId."<OwnerId>";
$PartnerIdList = "<PartnerIdList><String>".$xml->Partnership->PartnerIdList->String."</String></PartnerIdList>";
$CountryOrganizationId_contact = "<Contract><CountryOrganizationId>".$xml->Partnership->Contract->CountryOrganizationId."</CountryOrganizationId>";
$ContractId = "<ContractId>".$xml->Partnership->Contract->ContractId."</ContractId>";
$data .= "<Partnership>".$CountryOrganizationId.$PartnershipId.$OwnerId.$PartnerIdList.$CountryOrganizationId_contact.$ContractId.$Role1.$Category1.$Rate1.
$Role2.$Category2.$Rate2.$Role3.$Category3.$Rate3."</Partnership>";
}
echo $data;
Related
I already made my personal single thread proxy checker using php,but I couldnt make it multi-thread,some days ago,I found one checker using multi-thread on github,can someone help to change it to save the good proxies into a file (ip:port format)?
https://raw.githubusercontent.com/samuel-allan/FastProxyChecker/master/checker.php
What i have tried:
original line 91:
echo json_encode($arr);
changed to:
$json = json_decode($arr);
$good_proxie = $json['arr']['result']['proxy']['ip'];
echo "$good_proxie";
I did not checked it, but think it'll work ^_^
function CheckMultiProxy($proxies, $timeout, $proxy_type)
{
$data = array();
foreach($proxies as $proxy)
{
$parts = explode(':', trim($proxy));
$url = strtok(curPageURL(),'?');
$data[] = $url . '?ip=' . $parts[0] . "&port=" . $parts[1] . "&timeout=" . $timeout . "&proxy_type=" . $proxy_type;
}
$results = multiRequest($data);
$holder = array();
foreach($results as $result)
{
$holder[] = json_decode($result, true)["result"];
}
$arr = array("results" => $holder);
foreach ($arr['results'] as $proxy) {
if ($proxy['success']) {
file_put_contents('YOUR_FILE_HERE', $proxy['proxy']['ip'].':'.$proxy['proxy']['port'].' '.$proxy['proxy']['type'].PHP_EOL, FILE_APPEND);
}
}
echo json_encode($arr);
}
I have a Api response in XML format.How can I get gps_x and gps_y for both elements.
$url="http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo";
$xmlinfo = simplexml_load_file($url);
print_r($xmlinfo);
echo $xmlinfo['gps_x']; // outputs nothing
echo $xmlinfo -> gps_x; // outputs nothing
How can I get gps_x and gps_y from above response?
I did this by getting the content from url then converting to json using exceptions handling and get the data from decoded json:
<?php
$myXMLData = file_get_contents("http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo");
$simpleXml = simplexml_load_string($myXMLData) or die("Error: Cannot create encode data to xml object");
$jsondata = json_encode($simpleXml) or die("Error: Cannot encode record to json");
$data = json_decode($jsondata, true);
$in = $data['items']['item'];
foreach ($in as $key => $value) {
echo "ID= " . $in[$key]['id'] . ", GPS-x = " . $in[$key]['gps_x'] . ", GPS-y = " . $in[$key]['gps_x'];
echo "<br/>";
}
?>
OUTPUT
ID= 2354292, GPS-x = 36.1065000000, GPS-y = 36.1065000000
ID= 2431066, GPS-x = 36.0949905151, GPS-y = 36.0949905151
If you want to take the data from XML directly:
<?php
$myXMLData = file_get_contents("http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo");
$simpleXml = simplexml_load_string($myXMLData) or die("Error: Cannot create encode data to xml object");
$in = $simpleXml->items->item;
foreach ($in as $key) {
echo "ID= " . $key->id;
echo ", GPS-x = " . $key->gps_x;
echo ", GPS-y = " . $key->gps_y . "<br/>";
}
?>
OUTPUT
ID= 2354292, GPS-x = 36.1065000000, GPS-y = 28.0684000000
ID= 2431066, GPS-x = 36.0949905151, GPS-y = 28.0860328674
Looking at the print_r() output, it show that the gps_x & gps_y are part of an item and not directly under the xmlinfo object.
Here is the code that will do the job:
$url = "http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo";
$xmlinfo = simplexml_load_file($url);
if ($xmlinfo->items && $xmlinfo->items->item) {
$item = $xmlinfo->items->item;
print $item->gps_x . "\n";
print $item->gps_y . "\n";
}
$url="http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo";
$xmlinfo = simplexml_load_file($url);
foreach ($xmlinfo->items->item as $item) {
//echo "<pre>";print_r($item);
echo "<br />". $item->gps_x;
echo "<br />". $item->gps_y;
}
I wrote some code to update a mySQL table via php/PDO.
But it is not working and I just can't figure out where my mistake is.
The execute() returns true, but the changes never actually show up in the table.
My code looks pretty much like this:
$columnObject = array(
"emailAddress"=>"aaa#aaa.com",
"passwordHash"=>"56bj5g63j4g57g567g5k75jh7gk4g74j5hg67",
"name"=>"qweqweqwe",
"lastActivity"=>4128649814
);
$knownColumnName = "emailAddress";
$knownColumnData = "aaa#aaa.com";
foreach ($columnObject as $columnName => $columnData) {
$pdoUpdateString .= $columnName . "=:" . $columnName . ",";
$pdoExecuteObject[$columnName] = $columnData;
}
$pdoUpdateString = rtrim($pdoUpdateString, ",");
$pdoExecuteObject['knownColumn'] = $knownColumnData;
$q = $this->hCon->prepare('UPDATE ' . $this->name . ' SET ' . $pdoUpdateString . ' WHERE ' . $knownColumnName . '=:knownColumn');
$q->execute($pdoExecuteObject);
Ok some php code below.
$user_pass = "
vortex90:OPFY4MB8
jimmy3:3M7ISWof
dave-ish-mental:YEnMMXua
cindybaby:rRHxrErp
claire-x:H4VrT8Xx
icemonster:ODId9N17
";
$token = 'token';
$ex = explode("\r", $user_pass);
foreach ($ex as $info) {
print "username=" . str_replace(":", "&password=", $info) . "&token=" . $token . "\n";
}
What i want the foreach() to do is show for each explode
username=username&password=password&token=token
But below is what gets returned.
vortex90&password=OPFY4MB8
jimmy3&password=3M7ISWof
dave-ish-mental&password=YEnMMXua
cindybaby&password=rRHxrErp
claire-x&password=H4VrT8Xx
icemonster&password=ODId9N17
Why is it not returning as expected? all answers welcome.
This works for me, it is better practice to use PHP_EOL:
$token = "bla";
$user_pass = "
vortex90:OPFY4MB8
jimmy3:3M7ISWof
dave-ish-mental:YEnMMXua
cindybaby:rRHxrErp
claire-x:H4VrT8Xx
icemonster:ODId9N17
";
$explode = explode(PHP_EOL, $user_pass);
foreach($explode as $i) {
$replace_shit = str_replace(array("\r","\n",":"), array("","","&password="), $i);
$user_info = "username=".$replace_shit."&token=".$token."<br>\n";
echo $user_info;
}
DEMO: http://sandbox.onlinephpfunctions.com/code/02f6663f7fa69c158a90fde2ab421cf52a78f7ce
I've been trying to use XPath in PHP to access an Atom feed from the National Health Service API.
The data looks like this:
<feed xmlns:s="http://syndication.nhschoices.nhs.uk/services" xmlns="http://www.w3.org/2005/Atom">
<title type="text">NHS Choices - GP Practices Near Postcode - W1T4LB - Within 5km</title>
<entry>
<id>http://v1.syndication.nhschoices.nhs.uk/organisations/gppractices/27369</id>
<title type="text">Fitzrovia Medical Centre</title>
<updated>2011-08-20T22:47:39Z</updated>
<link rel="self" title="Fitzrovia Medical Centre" href="http://v1.syndication.nhschoices.nhs.uk/organisations/gppractices/27369?apikey="/>
<link rel="alternate" title="Fitzrovia Medical Centre" href="http://www.nhs.uk/ServiceDirectories/Pages/GP.aspx?pid=303A92EF-EC8D-496B-B9CD-E6D836D13BA2"/>
<content type="application/xml">
<s:organisationSummary>
<s:name>Fitzrovia Medical Centre</s:name>
<s:address>
<s:addressLine>31 Fitzroy Square</s:addressLine>
<s:addressLine>London</s:addressLine>
<s:postcode>W1T6EU</s:postcode>
</s:address>
<s:contact type="General">
<s:telephone>020 7387 5798</s:telephone>
</s:contact>
<s:geographicCoordinates>
<s:northing>182000</s:northing>
<s:easting>529000</s:easting>
<s:longitude>-0.140267259415255</s:longitude>
<s:latitude>51.5224357586293</s:latitude>
</s:geographicCoordinates>
<s:Distance>0.360555127546399</s:Distance>
</s:organisationSummary>
</content>
</entry>
</feed>
I'm now using this code to access the node.
<?php
$feedURL = 'http://v1.syndication.nhschoices.nhs.uk/organisations/pharmacies/postcode/W1T4LB.xml?apikey=&range=5';
$xml = file_get_contents($feedURL);
$sxml = new SimpleXMLElement($xml);
$sxml->registerXPathNamespace('a', 'http://www.w3.org/2005/Atom');
$sxml->registerXPathNamespace('s', 'http://syndication.nhschoices.nhs.uk/services');
$addr = $sxml->xpath('//s:address');
var_dump($addr[0]);
?>
Here $addr is empty but it should have ten entries.
Please can someone explain a good way to print out each <s:addressLine> node contents, and to place the postcode into a var.
I am working with the namespace principle in practice, although this is fairly new to me. Appreciate any information you could convey about learning XPath, and the PHP SimpleXML model.
Appreciate the help.
EDIT -
In seeing the update given below I decided to put my final output code into this:
function doPharmacy($postcode, $request, $prev, $next)
{
$feedURL = 'http://v1.syndication.nhschoices.nhs.uk/organisations/pharmacies/postcode/' . $postcode . '.xml?apikey=&range=5';
$xml = file_get_contents($feedURL);
$sxml = new SimpleXMLElement($xml);
$sxml->registerXPathNamespace('a', 'http://www.w3.org/2005/Atom');
$sxml->registerXPathNamespace('s', 'http://syndication.nhschoices.nhs.uk/services');
////////////// XPATH \\\\\\\\\\\\\\
$addrLines = $sxml->xpath('/a:feed/a:entry[' . $request . ']/a:content/s:organisationSummary/s:address/s:addressLine');
$nhsPostcode = $sxml->xpath('/a:feed/a:entry[' . $request . ']/a:content/s:organisationSummary/s:address/s:postcode');
$tel = $sxml->xpath('/a:feed/a:entry[' . $request . ']/a:content/s:organisationSummary/s:contact/s:telephone');
$distance = $sxml->xpath('/a:feed/a:entry[' . $request . ']/a:content/s:organisationSummary/s:Distance');
$title = $sxml->xpath('/a:feed/a:entry[' . $request . ']/a:title');
$link = $sxml->xpath('/a:feed/a:entry[' . $request . ']/a:link[#rel="alternate"]/#href');
$nhsPostcode = array_pop($nhsPostcode); // always taking first node from set
$tel = array_pop($tel);
$distance = (double)array_pop($distance);
$title = array_pop($title);
$link = array_pop($link);
////////////// OUTPUT: JSON \\\\\\\\\\\\\\
print '{"addr": "';
foreach ($addrLines as $addr)
{
print $addr . '<br />'; // ok to use HTML tags in JSON
}
print '",';
print '"postcode": "' . $nhsPostcode . '",';
print '"tel": "' . $tel . '",';
$num = number_format($distance, 2);
print '"distance": "' . $num . '",';
print '"title": "' . $title . '",';
print '"link": "' . $link . '",';
$nhsPostcode = urlencode($nhsPostcode);
print'"mapsURL": "http://maps.googleapis.com/maps/api/staticmap?center=' . $nhsPostcode . '&zoom=15&size=155x137&sensor=false&scale=2",';
print '"prev": "' . $prev . '",';
print '"next": "' . $next . '"';
print '}';
}
?>
This works for me:
$addr = $sxml->xpath('//s:address');
foreach ($addr as $a) {
$addressLine = $a->xpath('s:addressLine');
foreach ($addressLine as $al) {
echo (string)$al."<br/>";
}
$postalCode = $a->xpath('s:postcode');
foreach ($postalCode as $p) {
echo (string)$p."<br/>";
}
}
Which displays:
31 Fitzroy Square
London
W1T6EU
Previous answers have helped me a lot! So here go the complete solution.
$feedURL = "http://v1.syndication.nhschoices.nhs.uk/organisations/pharmacies/postcode/{$user->postcode}.xml?apikey=XXXX&range=100";
$xml = simplexml_load_file($feedURL);
$xml->registerXPathNamespace('s', 'http://syndication.nhschoices.nhs.uk/services');
$org = $xml->xpath('//s:organisationSummary');
$i = 0;
$item = array();
foreach ($org as $o)
{
$aux = $o->xpath('s:name');
$item[$i]['name'] = (string) $aux[0];
$addr = $o->xpath('s:address');
foreach ($addr as $a)
{
$aux = '';
$addressLine = $a->xpath('s:addressLine');
foreach ($addressLine as $a2)
{
$aux .= (string) $a2[0] . "\n";
}
$aux2 = $a->xpath('s:postcode');
if (is_array($aux2))
{
$aux .= (string) $aux2[0];
}
$item[$i]['address'] = $aux;
}
$i ++;
}
This will provide:
array (
0 =>
array (
'name' => 'Your Local Boots Pharmacy',
'address' => 'Century House
Station Road
Manningtree
CO11 1AA',
),
1 =>
array (
'name' => 'The Pharmacy',
'address' => 'The Street
East Bergholt
CO7 6SE',
), and so on...