I am trying to recover only some values from an xlsx file. The file that creates problems for me is worksheets / sheet1.xml whose structure is ...
<sheetData>
<row (attribbutes)>
<c (attributes)>
<v>value</v>
</c>
.....
<c (attributes)>
<v>value</v>
</c>
</row>
......
<row (attribbutes)>
<c (attributes)>
<v>value</v>
</c>
.....
<c (attributes)>
<v>value</v>
</c>
</row>
</sheetData>
my problem is that the values that interest me are in different lines but they can be the same. For example: I need the number of the day of the month (eg 16), but that number is also the pointer that allows me to find the name of a colleague and when I read the attributes of the row I don't find what I expect. Following is the code I use
$sheet1 = 'sheet1.xml';
$getrow = file_get_contents($sheet1);
$xmlrow = simplexml_load_string($getrow);
foreach ($xmlrow->sheetData->row as $row_0) {
foreach ($row_0->c as $c_0)
{
foreach ($c_0->v as $v)
{
if ($v[0] == $preserve) /****** This changes when search for number day of the month (if $v == $day)
{
$attr_0 = $c_0->attributes();
$row = $attr_0['r'];
break 3;
}
}
}
}
How can I get the correct value in the correct row?
Rather than scanning through the entire structure, you can use XPath to find it for you. This code looks for a <c>
element with a value ( <v>
element) equal to the value you are after.
As xpath()
returns an array of matches, this means you need to use $cell[0]
, adding on the ['r']
will then give you the attribute.
$getrow = file_get_contents($sheet1);
$xmlrow = simplexml_load_string($getrow);
$cell = $xmlrow->xpath('//c[v="'.$preserve.'"]');
echo $cell[0]['r'];
Test file...
<sheetData>
<row r="4" customFormat="false" ht="12.75" hidden="false"
customHeight="true" outlineLevel="0" collapsed="false">
<c r="A4" s="12" />
<c r="B4" s="13" t="n">
<v>1</v>
</c>
<c r="C4" s="13" t="n">
<v>2</v>
</c>
<c r="D4" s="13" t="n">
<v>3</v>
</c>
<c r="E4" s="13" t="n">
<v>4</v>
</c>
<c r="F4" s="14" t="n">
<v>5</v>
</c>
<c r="G4" s="13" t="n">
<v>6</v>
</c>
....
</row>
</sheetData>
and using the following...
$preserve = 2;
gives me
C4
Problem solved. In the above code $row = $attr_0['r'];
$row becomes an array $row[] and analyze it. Thank Nigel Ren for givin me an inspiration
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.