Php xml parsing for element value - php

i have the following xml returned from a jsp call
<assumption name="test" id="34" description="vector description" is_shared="no" vector_type="Prepay">
<userVector>
<vectorType>"Prepay"</vectorType>
<ppydefTypeCode>"CDR"</ppydefTypeCode>
<ppydefVector>
<vectorName>"test"</vectorName>
<vectorSeasoning>No</vectorSeasoning>
<vectorPeriod>"6 12"</vectorPeriod>
<vectorData>"7 4"</vectorData>
</ppydefVector>
</userVector>
</assumption>
What is the best way to retrieve the vectorType information and vectorName using php .
I tried something similar but was not sure how to grab the node value in php
foreach ($xmlDoc->getElementsByTagName('userVector') as $vectorRow)
{
$vectorType = $xmlDoc->getElementsByTagName('vectorType');
}

getElementsByTagName('vectorType') will return a DOMNodeList that you'll additionally have to iterate through. You can save each element's value to a variable by accessing their nodeValue fields.
foreach ($xmlDoc->getElementsByTagName('userVector') as $vectorRow){
$vectorTypes = $vectorRow->getElementsByTagName('vectorType');
foreach ($vectorTypes as $vectorTypeElement){
$vectorType = $vectorTypeElement->nodeValue;
}
}

Try this:
$sx = new SimpleXMLElement($XMLData);
echo $sx->xpath('/assumption/userVector/vectorType')[0];
echo $sx->xpath('/assumption/userVector/ppydefVector/vectorName')[0];
Outputs:
"Prepay"
"test"

Related

Getting name spaces out of XML from simplexml_load_file in php

I am trying to parse this YouTube XML using simplexml_load_file in php.
The XML feed can be found here:
https://www.youtube.com/feeds/videos.xml?playlist_id=PL1mm1FfX5EHRjGyoBpEXBRIGAmCNt8pBT
Below in php I am trying to iterate through the media groups nested inside each entry node.
<?php
$xmlFeed=simplexml_load_file('https://www.youtube.com/feeds/videos.xml?playlist_id=PL1mm1FfX5EHRjGyoBpEXBRIGAmCNt8pBT')
or die("Cannot load YouTube video feed, please try again later.");
foreach ($xmlFeed->entry->children('media', true)->group as $video) {
echo $video->title;
echo $video->description;
echo $video->thumbnail->getNameSpaces(true);
}
?>
Title and description print just fine. But I'm trying to get at the thumbnail URL found in this namespace:
<media:thumbnail url="https://i1.ytimg.com/vi/HEYQXVGnwXc/hqdefault.jpg" width="480" height="360"/>
I've tried all 3 of the following:
echo $video->thumbnail->getNameSpaces(true);
echo $video->thumbnail->getNameSpaces(true)['url'];
echo $video->thumbnail->getNameSpaces(true)->url;
None return the url. The first returns Array and the last two are blank. What am I missing?
Several things: first, you have to use the attributes() function since there is no child of thumbnail. Secondly, you don't need to declare getNameSpaces(true) since the namespace prefix media is done in the for loop. Finally, you do not iterate across all media:group. Right now, you will return only the first set of xml values, not both from each <entry> node. Therefore, you need to add an outer loop -one that iterates across the frequency of <entry> nodes.
$attr = 'url';
for($i = 0; $i < sizeof($xmlFeed->entry); $i++) {
foreach ($xmlFeed->entry[$i]->children('media', true)->group as $video) {
echo $video->title."\n";
echo $video->description."\n";
echo $video->thumbnail->attributes()->$attr."\n";
}
}
XPATH Alternative
Even further, you could have handled your needs in XPath by simply registering the media namespace and querying to exact locations, iterating of course across each set:
$xmlFeed->registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');
// ARRAYS TO HOLD XML VALUES
$videos = $xmlFeed->xpath('//media:group');
$title = $xmlFeed->xpath('//media:group/media:title');
$description = $xmlFeed->xpath('//media:group/media:description');
$url = $xmlFeed->xpath('//media:group/media:thumbnail/#url');
// ITERATING THROUGH EACH ARRAY
for($i = 0; $i < sizeof($videos); $i++) {
echo $title[$i]."\n";
echo $description[$i]."\n";
echo $url[$i]."\n";
}

PHP: How to change part of XML using DomElement

I am trying to make a function that changes part of an XML using XPath. I used part of someone else post:
/*********************************************************************
Function to replace part of an XML
**********************************************************************/
function replacePartofXML($element, $methodName, $methodValue, $xml, $newPartofXML)
{
$xpathstring = "//" . $element . "[#$methodName = \"$methodValue\"]";
$xml->xpath($xpathstring);
//$domToChange = dom_import_simplexml($xml->xpath($xpathstring));
$domToChange = dom_import_simplexml($xml);
$domReplace = dom_import_simplexml($newPartofXML);
$nodeImport = $domToChange->ownerDocument->importNode($domReplace, TRUE);
$domToChange->parentNode->replaceChild($nodeImport, $domToChange);
return($xml);
}
What I want to do is return the appended XML. I can't use dom_import_simplexml($xml->node->node) as my XML has many repeating element (but they have different ID reason why I am trying to use xpath)
The commented line does not work either as xpath returns an array and dom_import_simplexml is cannot import arrays.
Thanks for you input
You can take the first element returned by xpath() in case you believe the target element is unique (no-element-returned checking omitted) :
$domToChange = dom_import_simplexml($xml->xpath($xpathstring)[0]);
or iterate through the return value of xpath() and replace one by one.

Using PHP to get xml selector attributes

I am trying to access the xml attributes using php. I can access the actual text of any field, but
For example, a line from the xml file looks like this:
<Competitor CODE1="MIN" CODE3="MIN" CODE4="l.mlb.com-t.10" ID="69" LineOrderOverride="" NAME="Minnesota Twins" NUM="1" ROT="927" SCORE="5">Game 1</Competitor>
The code I am using will show me "Game 1" but I want to be able to access the NAME and SCORE values
#$doc->load($feedURL);
$arrFeeds = array();
foreach ($doc->getElementsByTagName('Event') as $node) {
$itemRSS = array (
echo strip_tags(str_replace("'","",$node->getElementsByTagName('Competitor')->item(0)->nodeValue));
};
Does anyone know a way to access the meta variables using PHP?
Inside your foreach(), add
echo $node->getElementsByTagName('Competitor')->item(0)->getAttribute("NAME"); // For NAME
echo $node->getElementsByTagName('Competitor')->item(0)->getAttribute("SCORE"); // For SCORE

xpath search for a php variable

I am trying to search for a php variable in an xml file using xpath, but failing miserably. It works with a hard coded value, so I am nearly there..
<visitors>
<detail>
<id>876867</id>
<name>Bob McHaggis</name>
<email>bob#gmail.com</email>
</detail>
<detail>
<id>897987</id>
<name>Mark McBob</name>
<email>mark#gmail.com</email>
</detail>
</visitors>
<?php $sxe = simplexml_load_file("/CaptivePortal/visitors.xml");
foreach($sxe->xpath('//visitors/detail') as $item){
$row = simplexml_load_string($item->asXML());
$v = $row->xpath('//id[. ="'.$_COOKIE["judsons"].'"]');
} echo $v[0]; ?>
This works great checks for an id against the id stored in the cookie. But based on that value being found how do I access the name and email for the key matched?
Found & matched: 897987
I want to echo the name and email to, so based on that is Mark McBob & mark#gmail.com
My initial advice would be to take a good few minutes to (re-)read through the SimpleXML Basic Usage page in the PHP manual.
For selecting a single item within the XML file, there is no need at all to loop over anything. The example code below, and why it is different from yours, should become clear after familiarising yourself with the page mentioned above.
<?php
$search_id = (int) $_COOKIE["judsons"];
$visitors = simplexml_load_file("/CaptivePortal/visitors.xml");
$details = $visitors->xpath("detail[id='$search_id']");
if (empty($details)) {
echo "No details found for '$search_id'.";
} else {
$detail = $details[0];
$name = (string) $detail->name;
$email = (string) $detail->email;
echo "$name's email is $email";
}
The idea above is that $details will be an array containing hopefully just one <detail> element. It could be an empty array if no <detail> was found with the specified <id>, which is what the if(empty(…)) checks for. If the $details array is not empty, we're really only interested in the first one ($details[0]).
To access the information available within the <detail>, as explained on the "basic usage" page, the elements can be accessed with normal object property syntax ($detail->name). Doing so returns an object for that item (e.g. the <name>), so to get at the value as a string the object is type cast using (string).
You're actually doing quite a bit you don't need to there. For one thing, you don't need the loop. For another, inside your loop, you convert the context XML into a string (::asXML()), then convert it back into XML (simplexml_load_string()).
All you need is:
$xml = "<visitors><detail><id>876867</id><name>Bob McHaggis</name><email>bob#gmail.com</email></detail><detail><id>897987</id><name>Mark McBob</name><email>mark#gmail.com</email></detail></visitors>";
$sxe = simplexml_load_string($xml);
$row = $sxe->xpath('detail[id = '.$_COOKIE["judsons"].']');
That gets you the row. To extract part of it:
$name = $row[0]->xpath('name');
echo $name[0]; //Mark McBob

PHP Retrieve DATA from XML

My first attempt at retrieving data from XML for a maps application has failed. Here is a piece of the XML Feed.
<?xml version="1.0" encoding="UTF-8"?>
<DirectionsResponse>
<status>OK</status>
<route>
<leg>
<start_address>Winkfield, Bracknell, Berkshire RG42 6LY, UK</start_address>
<end_address>Wentworth, Surrey GU25 4, UK</end_address>
</leg>
</route>
</DirectionsResponse>
I want to get the start and end address and return them via AJAX to the application.
The PHP
<?php
$start = $_POST['start'];
$end = $_POST['end'];
$xml = simplexml_load_file('http://maps.googleapis.com/maps/api/directions/xml?origin='.$start.'&destination='.$end.'&sensor=false');
// data to fetch
$start = $xml->xpath("/DirectionsResponse/route/leg/start_address");
$end = $xml->xpath("/DirectionsResponse/route/leg/end_address");
$start = array($start);
// output
echo json_encode( array('output'=>$start[0]));
?>
Annoyingly this is returning an object to the page.
Response :: {"output":[{"0":"Winkfield, Windsor, Berkshire SL4 2ES, UK"}]}
Anyone know how to stop that from happening. I just want the value Winkfield, Windsor, Berkshire SL4 2ES, UK.
Haven't tested your specific case, but i remember running into something similar when using SimpleXML, you might want to use (string) to cast it out of the object
array('output'=> (string)$start[0])
Or rather just leave out $start = array($start) and just do
array('output'=> (string)$start)
On reading the SimpleXML XPath documentation (http://www.php.net/manual/en/simplexmlelement.xpath.php) again i think your problem might be this:
Returns an array of SimpleXMLElement objects or FALSE in case of an error.
So the XPath returns an array, then you wrap that in an array and take the first element of that array, so all you end up with is the original array - remove the array wrap and you should be fine
function XMLReader()
{
$MyArray = array();
$doc = new DOMDocument();
$doc->load( 'XMLFilePath.xml' );
$info = $doc->getElementsByTagName( "leg" );
foreach( $info as $Type )
{
$details = $Type->getElementsByTagName( "start_address" );
$detail = $details->item(0)->nodeValue;
$MyArray [] = $detail;
}
return $MyArray;
}
and same for end_Address.
I wish this answer is helpful.
Just echo $start? Also, why do you make an array of start and then output the first element, it doesnt make any sense at all.
echo $xml->route->leg->start_address;
This is the edited answer. I checked it. Its working properly on the XML.

Categories