I have a bunch of dom manipulation functions within a class.
One of those functions assigns unique ids to specific nodes.
$resource_info_node->setAttribute('id', 'resource_'.$this->ids);
$details['id'] = 'resource_'.$this->ids;
$details['node'] = $resource_info_node;
$this->resource_nodes['resource_'.$this->ids] = $details;
$this->ids += 1;
later I want to look up and modify those nodes.
I have tried :
$current_node = $this->resource_nodes[$id]['node'];
When I print_r() I find that this node is a duplicate of the original node.
It has the original node's attributes but is not a part of the DOM tree.
I get the same results with :
$this->content->getElementById($id);
I suppose I based this whole thing on storing node references in an array. I thought that was a fine thing to do. Even if not, after that using getElementByID() should have returned the node within the dom.
I thought that, in PHP all objects were passed by reference. Including DOM nodes.
Any ideas on how I can test what is actually going on.
EDIT :
Well I used :
$this->xpath->query('//*[#id]');
That returned the right number of items with ids. The node is just not in the DOM tree when I edit it.
and
$current_node = &$this->resource_nodes[$id]['node'];
Using the reference syntax had no affect.
The strangest part is that get elementById() is not returning a node in the dom. It has all the right attributes except no parentNode.
FIX - not answer :
I just used xpath instead of my reference or getElementById().
Use reference explicity:
$current_node = &$this->resource_nodes[$id]['node'];
And modify $current_node
Related
I have to filter portions of a JSON, there are different nodes/sub-nodes and I really need only a portion, for example this is what it may look like:
"node1":{
"686":{
"value1":"686",
"value2":"M",
"value3":0
}
"687":{
"value1":"687",
"value2":"L",
"value3":1
}
"688":{
"value1":"688",
"value2":"M",
"value3":0
}
For example I need to extract the node1 nodes, specifically ["686","687","688"] what I have tried so far:
$node1values = array_keys((array)$myjson->node1)
The response is weird: * items consider that I never use PHP regularly, no idea how to get this sorted without having to write a procedure to iterate every possible node.
Use array_column() to get a particular property from each array element.
$node1values = array_column((array)$myjson->node1, 'value1');
DEMO
I'm having trouble parsing XML with Namespaces using SimpleXMLElement.
I've tried using looping through the xml and also tried using xpath without success.
$data_url="http://isni.oclc.nl/sru/0000000123121970?query=pica.isn+%3D+%220000000123121970%22&version=1.1&operation=searchRetrieve&stylesheet=http%3A%2F%2Fisni.oclc.nl%2Fsru%2FDB%3D1.2%2F%3Fxsl%3DsearchRetrieveResponse&recordSchema=isni-b&maximumRecords=10&startRecord=1&recordPacking=xml&sortKeys=none&x-info-5-mg-requestGroupings=none";
$data = file_get_contents($data_url);
$xml = simplexml_load_string($data);
$org_names = $xml->children('srw', true)->records->children('srw', true)->record->children('srw', true)->recordData->responseRecord->isniassigned->isnimetadata->identity->organisation->organisationnamevariant->mainname;
foreach($org_names as $a)
{
echo "a: $a\n";
}
I'm expecting to get a list of organisationnamevariant->mainname items:
Academia lugduno-batava
Leiden university
Leidse universiteit
etc.
However, I'm getting this error: Trying to get property of non-object
Having such a deep hierarchy is difficult to navigate using the normal -> structure, but you also have to be careful when changing namespace. You only need to do the ->children('srw', true) once and then all of the child nodes will be for that namespace. BUT you also have to switch back at <responseRecord> by using ->children().
You also need to be careful that you use the proper case for each tag name...
$org_names = $xml->children('srw', true)->records->record->recordData->children()->
responseRecord->ISNIAssigned->ISNIMetadata->identity->organisation->
organisationNameVariant->mainName;
echo (string)$org_names;
An alternative is to use XPath (as xpath() returns a list of matches, I use [0] to only use the first one)...
$org_names = $xml->xpath("//organisationNameVariant/mainName");
echo (string)$org_names[0];
I know that echo casts the value to a string, but if you use this in any other scenario, you may end up with a SimpleXMLElement instead, so I tend to add the case to string in just to make the point.
I have an application where the user writes XPath queries to use as source data from a given document. Sometimes they need just the contents of an element, sometimes they need the whole element itself. To my understanding they should be able to specify either text() or node() at the end of their query to choose which behavior.
But it seems like the way I get a string out of the SimpleXMLElement determines the behavior, regardless of the query.
When I cast the query to (string), it ALWAYS only returns inner XML.
(string) $xml->xpath('//document/head/Keywords')[0] ===
(string) $xml->xpath('//document/head/Keywords/node()')[0] ===
(string) $xml->xpath('//document/head/Keywords/text()')[0] ===
'17';
If I use ->saveXML(), it ALWAYS returns the entire tag.
$xml->xpath('//document/head/Keywords')[0]->asXML() ===
$xml->xpath('//document/head/Keywords/node()')[0]->asXML() ===
$xml->xpath('//document/head/Keywords/text()')[0]->asXML() ===
'<Keywords topic="611x27keqj">17</Keywords>';
Is there a single way that I can get a string, which allows my users to specify inner vs outer XML as a part of their XPath query?
The SimpleXML xpath() method always returns SimpleXMLElement objects representing either an element or an attribute, never text. The methods you show in the question are the correct way to use that object to get text content or full XML.
If you want richer (but less simple) XPath functionality, you will have to use the DOM, and specifically the DOMXPath class. Note that you can freely mix SimpleXML and DOM using simplexml_import_dom and dom_import_simplexml; the internal representation is the same, so you can switch between the two "wrappers" with minimal cost.
I am a bit of a newbie to PHP and I'm not sure what I'm missing here. I have an multidimensional array that I've created from an XML file using XPath. I'm able to move through the array and retrieve most all values but I am getting stuck on one section.
Example of XML structure:
MasterNode
SubNodeItem1
SubNodeItem2
SubNodeItem3
SubNodeItemList
SubListItem
SubItemProperty1
SubItemProperty2
SubItemProperty3
SubItemList
SubItemProperty1
SubItemProperty2
SubItemProperty3
SubNodeItem4
SubNodeItem5
I am able to retrieve the value of any of the SubNode values by using the following syntax:
$val=$XML[$i]->SubNodeItem1;
however, I can not for the life of me figure out how to retrieve the values of SubListItemProperty.
I figured this would be the logical syntax:
$SubItemPropVal=$XML[$i]->SubNodeItemList->SubListItem[$i]->SubItemProperty1;
I have searched other forums and topics related to PHP multi arrays and have not been able to find the proper way to do this.
I am getting a "Trying to get property of non-object" error when I run the code. I'm pretty sure that's the indication that I'm not pointing the node correctly.
My recommendation would be to keep the XML file, which apparently works fine already, and use it.
Transferring its elements into an array does not make much sense to me.
EDIT: The OP does not actually use an array, but a SimpleXML object.
XPath is extremely flexible and powerful in selecting the needed bits from an XML document:
$doc = new DOMDocument();
$doc->loadXML($your_xml);
$xp = new DOMXPath($doc);
// for example
$result = $xp->query("//SubListItem[2]/SubItemProperty1");
if ($result->length)
{
echo $result->item(0)->textContent;
}
SimpleXML would also work:
$xml = simplexml_load_string($result);
// either this ($node will be an array of matches, or FALSE)
$node = $xml->xpath("//SubNodeItemList/SubListItem[1]/SubItemProperty1");
// or this (unless you add a number, [0] will be assumed)
$node = $xml->SubNodeItemList->SubListItem->SubItemProperty1;
Important: Array notation counts from 0, while XPath always counts from 1.
Note that the second option (array notation) will throw run-time errors when the structure of the document is not what your code expects.
With XPath there would simply be no return value, which is easier to handle (no try/catch block necessary, an if ($node) { ... } suffices).
Also note that with SimpleXML, the document element (<MasterNode>) becomes the document. So you would not use $xml->MasterNode->SubNodeItemList, but $xml->SubNodeItemList.
My Issue: Unable to append XML data to prexisting XML data in a MYSQL database.
I have an array - $buyer. Inside this array is a $key and $value similar to (shippingTotal => 55). What I want to do is use something similar to
$param = array(
'shippingTotal' => $shippingTotal
);
$where['quote_data = ?'] = $quoteNumber
$n = $db->update('quote_xml', simplexml_load_string($param), $where);
My hiccup is that the current data inside quote_data is an XML element containing LOTS of information. Is there any way to just "stick" shippingTotal into said existing XML? When I use the above code I just end up with quote_data becoming empty.
I also created a variable called $shippingTotal so that I wouldn't have to use $buyer['shippingTotal']. Still not functional.
Thank you for your time and assistance with this issue.
Aaron
I see a few issues with this:
First, simplexml_load_string doesn't accept array parameters, only XML strings. Since the $params is not a valid argument, it is returning boolean false. Even when successful, it returns a SimpleXMLElement. To convert that to an XML string, you would have to call the asXML() method on the returned object before passing it to Zend_Db_Table::update().
Second, most likely XML cannot just be "appended" to other XML. I don't know exactly what your table holds, but the XML needs to be programmatically added to the existing XML. You can't append XML because the data you want to add needs to be added to the proper nodes.
What you will have to do is first read the value of that column, parse it using SimpleXML, add your new data to the appropriate node in the document using one of the SimpleXML functions and then perform the update.
Hope that helps.